1、如何创建一个vuex实例?
1 | import Vue from 'vue' |
这样就创建了一个简单的Vuex实例store
,这个实例有两个属性:state
和 mutations
state
: 用于存储各种状态,类似Vue组件中的data
mutations
: 存储方法,用于修改state
中的各种状态(变量),类似于Vue组件中的methods
2、如何在Vue组件中使用state
和 mutations
?
首先声明一个组件Counter.vue
组件
1 | <template> |
这个组件模版依赖一个count
变量,和一个 increment
函数。
对于count
的值,会使用前面声明的Vuex
实例的state
属性中的count
的值。
对于increment
函数,会使用前面声明的Vuex
实例的mutations
属性中的increment
函数。
Tip: 记得在
main.js
中导入上面声明的store
, 并从根组件“注入”到每一个子组件中
1
2
3
4
5
6
7
8 import store from '@/store'
new Vue({
el: '#app',
store, // 注入store,这样在所有组件都可以使用this.$store获取实例
components: { App },
template: '<App/>'
})
Counter.vue
1 | export default { |
3、mapState 辅助函数是什么、有什么用、如何用?
mapState
是一个辅助函数- 帮我们生成计算属性
- 用法
1 | computed: mapState({ |