一、state 唯一数据源
main.js中添加
const store = new Vuex.Store ({ state: { count: 0 } })
new Vue({ store, render: h => h(App) }).$mount("#app")
使用方式一:(App.vue中)
<template> <h3>{{this.$store.state.count}}</h3> </template>
方式二:
<template> <h3>{{count}}</h3> </template> <script> export default { name: "app", computed: { count() { return this.$store.state.count; } }} </script>
二、mutation 更改store 中的状态的唯一方法是提交 mutation,同步函数
实现count++
main.js中
const store = new Vuex.Store ({ state: { count: 0 }, mutations: { countIncrease (state) { state.count++ } } })
App.vue中
<template> <div> <h3>{{count}}</h3> <input type="button" value="count自增" @click="countIncrease"> </div> </template>
<script> //...... methods: { countIncrease() { this.$store.commit('countIncrease') } } }; </script>
commit 可传state参数, 也可传额外的参数
mutations: { countIncrease (state,n) { state.count += n; } }
methods: { countIncrease() { this.$store.commit('countIncrease',100) } }
三、getter 有时候我们需要从 state 中派生出一些状态,例如对列表进行过滤并计数:
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) } } })
使用方式一:
<template> <div> <h1>{{this.$store.getters.doneTodos}}</h1> </div> </template>
如果有多个组件需要用到此属性,此方法不合适
使用方式二:
computed: { doneTodosCount () { return this.$store.state.todos.filter(todo => todo.done).length } }
<template> <div> <h1>{{doneTodosCount}}</h1> </div> </template>
四、action
Action 提交的是 mutation,而不是直接变更状态,Action 可以包含任意异步操作
Action 通过 store.dispatch
方法触发
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
<template> <div> <h1>{{count}}</h1> <button @click="increment">按钮</button> </div> </template> <script> export default { name: "app", computed: { count() { return this.$store.state.count } }, methods: { increment(){ this.$store.dispatch('increment') } } }; </script>
五、module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
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 的状态 store.state.b // -> moduleB 的状态