- 1.在src目录中新建store文件,store文件夹中新建index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// new Vuex.Store 创建对象
export default new Vuex.Store({
state:{
...共享的数据
count:0
},
// 对state中的数据进行处理,不会修改
getters:{
...方法
showNum(count){
return state.count
}
},
// 更新state中的数据,只能执行同步操作
mutations:{
... 方法
add(state){
state.count++
}
}
// 用于处理异步任务
actions: {
addAsync(context) {
setTimeout(() => {
// actions中,不能直接修改state中的数据
// 必须通过context.commit触发mutation中的函数执行
context.commit('add')
}, 1000)
},
vuex状态的所有改变都必须在store的mutation中进行修改
2.main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
// 使用el挂载
new Vue({
el:'#app',
render:h => h(App),
store,
})
3.子组件add.vue
<template>
<div>
<!-- this.$store.state访问全局共享数据 -->
<h3>当前最新的count:{{$store.state.count}}</h3>
<h3>
{{$store.getters.showNum}}
</h3>
<button @click="btnHandleAdd">+1</button>
</div>
</template>
<script>
export default {
data(){
return{
}
},
methods:{
// 同步操作 commit触发mutations操作
btnHandleAdd(){
this.$store.commit('add')
},
// 异步触发 dispatch触发actions操作
btnHandleAddAsync(){
this.$store.dispatch('addAsync')
},
}
</script>
- 获取变量名:this.$store.state.变量名