安装 Vuex
NPM
npm install vuex --save
#Yarn
yarn add vuex
一:创建一个 store
import Vue from 'vue'
import Vuex from 'vuex'
// 告诉 vue “使用” vuex
Vue.use(Vuex)
// 创建一个对象来保存应用启动时的初始状态
// 需要维护的状态
const store = new Vuex.Store({
state: {
// 放置初始状态 app启动的时候的全局的初始值
name: 0,
name: 'xiaogao'
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 `context.commit` 提交一个 mutation,或者通过 `context.state` 和 `context.getters` 来获取 state 和 getters。
incrementAsync (context) {
setTimeout(() => {
context.commit('increment')
}, 1000)
}
}
})
// 整合初始状态和变更函数,我们就得到了我们所需的 store
// 至此,这个 store 就可以连接到我们的应用中
export default store
二: 在vue根文件中注册全局store,这样所有的组件都可以使用store中的数据了
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './../store/index'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
三: 在组件中获取使用 store 中的数据和方法 (必须有第二步方可以在任意组件中使用store中的数据就方法)
<template>
<div class="common-layout layout-container-demo" >
<div >
{{name}}
</div>
<div >
{{count}}
</div>
<button @click="increment" >
count++
</button>
</div>
</template>
export default {
...
computed: {
name() {
return this.$store.state.name;
},
count() {
return this.$store.state.count;
},
},
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
},
increment2() {
this.$store.dispatch('incrementAsync')
console.log(this.$store.state.count)
},
}
...
}
四: 在 其他 js文件方法(非vue组件) 中使用 store 中的数据和方法
import store from './store'
store.commit('increment')
console.log(store.state.count)
// 或
store.dispatch('incrementAsync')
console.log(store.state.count)
下一篇文章将讲述 十分钟学会使用 Vuex 4.x (vue 3.x)