Vuex
Vuex
是在中大型项目中,用来管理一些变量的。因为如果项目比较大,一些数据在各个页面中可能需要进行交替使用,如果数据量比较大,通过params
或者query
的方式不太方便。这时候就可以使用Vuex
来管理这些数据。
安装:
- 通过
script
安装:<script src="https://cdn.jsdelivr.net/npm/vue@4.0.2/dist/vue.js"></script>
。 - 通过
npm
安装:npm install vuex@4.0.2 --save
。
基本使用:
每一个Vuex
应用的核心就是store(仓库)
。store
可以理解为就是一个容器,它包含着你的应用中大部分的状态(state)(就是变量)
。Vuex
和单纯的全局对象有以下两点不同:
Vuex
的状态存储是响应式的。当Vue
组件从store
中读取状态的时候,若store
中的状态发生变化,那么相应的组件也会相应地得到高效更新。- 你不能直接改变
store
中的状态。改变store
中的状态的唯一途径就是显式地提交(commit) mutation
。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
示例代码如下:
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)
然后在其他组件中,可以使用以下代码提交mutation:
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
}
mapState:
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用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
}
})
}
对象展开运算符:
有时候我们想要将vuex
中的变量添加到我们当前已有的computed
中。这时候就可以使用对象展开运算符:
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
getter:
有时候我们需要从store
中的state
中派生出一些状态,例如对列表进行过滤并计数:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果后期很多地方都要使用到这个变量,那么每次在组件中都写一遍肯定是不合适的,这时候就可以使用vuex
提供的getter
来实现:
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)
}
}
})