npm i vuex@3npm i vuex@4added 1 package in 2m,表示安装完成

// 引入Vue
import Vue from 'vue'
// 引入插件
import Vuex from 'vuex'
// 使用插件
Vue.use(Vuex)
// 负责执行行为的对象
const actions = {}
// 负责更新的对象
const mutations = {}
// 负责数据状态
const state = {}
// 负责接收state对象
const getters = {}
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
import store from './vuex/store'
new Vue({
el : '#app',
// 不要忘记这里也要添加
store,
render: h => h(App),
})


this.$store.commit('mutations的方法名', value)转到mutations// xxx.vue
methods : {
方法名(){
this.$store.dispatch('actions方法名', 值)
}
}
// 负责执行业务的对象
const actions = {
方法名(context, value){
......对value执行的业务
context.commit('这里写mutations的方法名', value)
}
}
this.$store.dispatch('actions方法名', 值)传过来的数据‘saveUsername’‘SAVE_USERNAME’this.$store.dispatch('actions方法名', 值),将数据传给actions,再通过context.commit('mutations方法名', value)传给mutations方法名中。// xxx.vue
methods : {
方法名(){
this.$store.dispatch('actions方法名', 值)
}
}
// 负责执行业务的对象
const actions = {
方法名(context, value){
......对value执行的业务
context.commit('这里写mutations的方法名', value)
}
}
// 负责更新数据的对象
const mutations = {
方法名(state, value){
......
}
}
this.$store.commit('mutations方法名', 值),将数据不经过actions的方式,直接传给mutations对象中。
// xxx.vue
methods : {
方法名(){
this.$store.commit('actions方法名', 值)
}
}
// 负责更新数据的对象
// mutations中的对象名,要和actions中的context.commit('mutations中的方法名')一致
const mutations = {
方法名(state, value){
......
}
}
// 负责数据状态
const state = {
xxx : '',
xxx : [
{id:xxx, name:xxx, age:xxx},
{id:xxx, name:xxx, age:xxx},
{id:xxx, name:xxx, age:xxx}
]
}
// xxx.vue
<template>
<div>
<h1>{{$store.getters.对象名}}</h1>
</div>
</template>
// 自动接收state对象,可对数据进行额外操作,产生不同的效果
// 效果:反转、去除空白行、转大小写 等等
const getters = {
方法名(state){
return ......
}
}