vuex是一个状态管理工具,可以实现数据的响应式,
看下图
vuex主要是有五个属性,state,actions,getters,mutations,modules,
state主要是声明变量;
通过this.$store.state.属性的方式来访问状态
mutations是一个方法,也可以传递两个参数
通过this.$store.commit(‘mutation中方法’)来修改状态
当传递两个参数时,
//第二个是值
store.commit('increment', 10)
//在mutations中这样使用
mutations: {
increment (state, n) {
state.count += n
}
}
//当第二个参数是对象的时候
store.commit('increment', {
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
//还可以如此
store.commit({
type: 'increment',
amount: 10
})
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
actions通常发送异步请求
方法调用
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
可以如此
store.dispatch('increment')
// dispatch with a payload
store.dispatch('incrementAsync', {
amount: 10
})
// dispatch with an object
store.dispatch({
type: 'incrementAsync',
amount: 10
})
module
const moduleA = {
state: () => ({ … }),
mutations: { … },
actions: { … },
getters: { … }
}
const moduleB = {
state: () => ({ … }),
mutations: { … },
actions: { … }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA
's state
store.state.b // -> moduleB
's state
getters是一个处理数据的
调用方法
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
modules是模块,
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> `moduleA`'s state
store.state.b // -> `moduleB`'s state
最后我们创建项目中步骤:
先安装vuex:npm install vuex --save
然后是创建文件夹:store,index.js文件
![目录结构](https://img-blog.csdnimg.cn/20210719172016453.png#pic_center
然后每个文件的内容
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import getters from './getters'
import actions from './actions'
Vue.use(Vuex)
const state = {
cartList: []
}
const store = new Vuex.Store({
state,
mutations,
getters,
actions
})
export default store
//actions
const actions = {
}
export default actions
//getters
const getters = {
}
export default getters
//mutations
const mutations = {
}
export default mutations