// 定义一个 Vuex store
const store = new Vuex.Store({
// state 是 Vuex 的状态树,包含应用的共享状态
state: {
count: 0
},
// mutations 是用于修改 state 的唯一方式,必须是同步函数
mutations: {
increment (state) {
state.count++
}
},
// actions 类似于 mutations,但可以包含异步操作
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
// getters 用于从 state 中派生出一些状态,类似于 Vue 组件中的 computed 属性
getters: {
doubleCount: state => state.count * 2
}
})
// 在组件中使用 store
new Vue({
el: '#app',
store,
computed: {
// 访问 Vuex store 中的状态
count () {
return this.$store.state.count
},
// 访问 Vuex store 中的 getter
doubleCount () {
return this.$store.getters.doubleCount
}
},
methods: {
// 触发 Vuex store 中的 mutation
increment () {
this.$store.commit('increment')
},
// 触发 Vuex store 中的 action
incrementAsync () {
this.$store.dispatch('incrementAsync')
}
}
})
this.$store 来访问和操作 Vuex store。上一篇:全局安装vue
下一篇:nginx部署vue刷新页面问题
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站