- 安装vuex,创建一个store文件夹index.js文件
npm install vuex
2.在index.js文件中导入vue和vuex,并全局使用vuex
import Vue from "vue"
import Vuex from 'vuex'
Vue.use(Vuex)//全局使用Vuex
//new 一个Vuex.Store({)}仓库
export default new Vuex.Store({
//自定义共享状态
state: {
isShow: true,
},
//自定义一个名称,用来修改状态,也是唯一用来修改状态的,它可以呗Devtools调试工具记录一切修改的状态。
mutations: {
//接收组件发送过来data,修改跟新state中的状态
hideTabBar(state, data){
state.isShow = data
},
showTabBar(state, data){
state.isShow = data
}
},
actions: {
}
})
3.在main.js中导入index,并使用。
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
4.在组件上可以直接获取store的状态,可以根据需求更改。
v-show="$store.state.isShow"
console.log(this.$store.state)//打印出store状态
this.$store.commit('hideTabBar', false)//发送修改store状态 mutations
this.$store.commit('showTabBar', ture)//将mutations里面的showTabBar改为ture
5.如果创建store遵循使用的程序创建,还可以通过vue-devtools调试器查看store内的所有状态的修改