vue-cli中vuex的使用

在项目的src文件下新建文件夹store,store之下再新建index.js。

在main.js中引入

import Vue from 'vue'
import App from './App'
import router from './router'
import store from'./store'  //引入store
Vue.config.productionTip = false

require('./mock.js')
import axios from './http/api.js'

Vue.prototype.$http = axios;
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  axios,
  components: { App },
  template: '<App/>'
})

在store>index.js中的代码结构

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

import * as types from './types'
import api from './../http/api.js'
const store = new Vuex.Store({
    state: {
        user: 'kuang',
        options: []
    },
    getters: {
        getUser(state){
            return state.user;
        }
    },
    mutations: {
        [types.SET_USER](state, value) {
            state.user = value
        },
        [types.SET_SELECT](state, value) {
            state.options = value
        }
    },
    actions: {
        setUser({ commit }, value){
            setTimeout(()=>{
                commit(types.SET_USER, value)
            },2000)
        },
        setSelect({ commit }, value) {
            return new Promise((resolve, reject)=>{
                api.$http('/news/select', '')
                .then(res => {
                    commit(types.SET_SELECT, res.data);
                    resolve();
                }).catch(error => {
                    reject();
                })
            })
        }    
    }
})

export default store;

store文件夹下新建types.js

export const SET_USER = 'setUser';
export const SET_SELECT = 'setSelect'

在组件中使用state

this.$Store.state.user  //直接获取store中的user

通过getter获取state

<script >
    import { mapGetters} from 'vuex' 
    export default {
        data(){
            return {
                msg: ''
            }
        },
        mounted(){
            this.msg = this.getUer()
        },
        methods: {
            ...mapGetters['getUser'],
        }
    }
</script>  

在组件中使用actions中的setSelect{},他回去找到mountation中的[types.SET_SELECT]方法

this.$store.dispatch('setSelect', '')  //触发setSelect方法

猜你喜欢

转载自www.cnblogs.com/hopesthwell/p/9256982.html