vuex
1.安装vuex
npm i vuex@3
2.在main.js中引入store
import Vue from 'vue';
import Antd from 'ant-design-vue';
import App from './App';
import store from './store'
// import router from './router'
import 'ant-design-vue/dist/antd.css';
Vue.config.productionTip = false;
Vue.use(Antd);
new Vue({
store,
render: h => h(App)
}).$mount('#app')
3.新建store文件夹,里面index.js,modules文件夹里建子模块
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 引入子store
import loginInfo from './modules/loginInfo'
// Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
loginInfo
}
})
export default store // 导出store,以便于后续使用
//modules文件夹里建子模块account.js
export default{
namespaced:true,
state:{
token:'12'
},
mutations:{
setToken(state,val){
state.token = val
}
}
actions: {
setToken: ({ commit },value) => {
commit('setToken', value)
},
}
}
在template中是modules的token
<template>
<div>
{{token}}
</div>
</template>
<script>
export default {
data(){
rerurn{
}
},
computed: {
token() {
//取state的值
return this.$store.state.loginInfo.token
},
created(){
this.getData()
}
methods:{
getData(){
const token = 1389
//通过commit调取mutations的方法修改state的值
this.$store.commit('loginInfo/setToken', token )
//dispatch:异步操作,通过dispatch调取mutations的方法修改state的值
this.$store.dispatch('loginInfo/setToken', token2)
}
}
},
}
</script>
commit:同步操作,写法: this.$store.commit(‘mutations方法名’,值)
dispatch:异步操作,写法: this.$store.dispatch(‘mutations方法名’,值)