1、在vue项目中①:使用命令yarn add vuex安装vuex插件②:新建文件命名为store.js,在文件中引入vue和vuex并使用vuex③构建新的Vuex.store对象,传入作为参数的对象,对象中包含基本的state、getter、mutations、actions四个属性。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
x:0,
},
getters:{},
mutations:{},
actions:{},
})
2、将store.js文件引入到main.js文件中,将store作为子属性传入构建出vue对象。这样在全局都可以访问到store中存储的数据。
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
3、这样就可以在任何vue文件中通过this.$store.state来访问数值了。
{ {a}}
export default {
name: 'app',
data(){
return{
a:1,
}
},
created(){
this.a = this.$store.state.x;
console.log(this.a)
}
}