一直以为项目里面的store是js的什么高级用法,今天看了一下原来是个插件
下面是官方文档的总结
vuex的核心是store,包含着应用中大部分的状态
1、Vuex的状态存储是响应式的,当VUE组件从store中读取状态的时候,若store中的状态发生变化,相应的组件也会得到高效的更新
2、不能直接改变store中的状态,除了commit
import { createApp } from 'vue'
import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
const app = createApp({ /* 根组件 */ })
// 将 store 实例作为插件安装
app.use(store)
通过store.state获取状态对象,commit触发状态变更
store.commit('increment')
console.log(store.state.count) // -> 1
通过this.$store访问实例
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
}
核心概念
State
推荐在计算属性中访问state
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
对象展开运算符
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
Getter
使用Getter可以在获取state的时候进行一些处理
const store = createStore({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
}
})
使用时 store.getters.doneTodos
Getter也可以接受其他getter作为第二个参数
如果让getter返回一个函数,就可以实现给getter传参了
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
使用:store.getters.getTodoById(2)
mapGetters:将store中的getter映射到局部计算属性
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果想给getter属性另外命名,使用对象形式
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
Mutation
进行state的变更
Action
类似于mutation,不同点为
1、Action提交的是mutation,不是直接变更状态
2、Action可以包含任意异步操作
mutation必须同步执行,但使用store.diapatch来分发action就没有这个限制了
Module
将store分割成模块module,每个模块拥有自己的state、mutation、action、getter