Vuex 和单纯的全局对象有以下两点不同:
1 Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
使用:
–安装vuex:npm i vuex -s
–在项目的根目录下新增一个store文件夹,在该文件夹内创建index.js
此时你的项目的src文件夹应当是这样的
│ App.vue
│ main.js
│
├─assets
│ logo.png
│
├─components
│ HelloWorld.vue
│
├─router
│ index.js
│
└─store
index.js
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
globalLoading:false,
},
mutations: {
toggleLoading(state,payload=false){
state.globalLoading=payload;
}
},
actions: {
},
modules: {
}
})
main.js
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
zujian.vue
methods:{
initTaskInfo(taskID){
this.$store.commit('toggleLoading',true);
},
}