vuex的使用

 1. 搭建vue脚手架,安装vuex依赖

npm i vuex -S

2. 项目目录src下新建store目录和index.js文件

import Vue from 'vue'
import Vuex from 'vuex'

// 让vue使用vuex工具来实现组件之间的数据共享
Vue.use(Vuex)

const state = {
    managerActive:"",
}
const mutations = {
    setManagerActive(state,str){
        state.managerActive = str;
    },
   
}
const actions = {}
const getters = {
    getManagerActive(state){
        return state.managerActive;
    }
}
export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

通常设计store对象都包含4个属性:state,getters,actions,mutations。
如何理解这4个属性呢,从自己的话来理解:

state (类似存储全局变量的数据)
getters (提供用来获取state数据的方法)
actions (提供跟后台接口打交道的方法,并调用mutations提供的方法)
mutations (提供存储设置state数据的方法)

 

 

 

3. 在main.js中引用vuex

import store from './store'




new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

4. 如何在vue中使用

//通过commit调用放方法setManagerActive修改 数据
 this.$store.commit('setManagerActive','first');

//通过getters调用方法getManagerActive 获取数据
this.$store.getters.getManagerActive

 

posted @ 2021-11-17 14:15  hjMa  阅读(26)  评论(0编辑  收藏  举报