vuex的用法
- export可以使用多次,引入需要加{}
- export default 一个页面只能使用一次,可以直接引入
npm i vuex
//store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
export 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)
}
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
},
actions: {
increment ({ commit },data) {
//异步方法,获取到data
commit('increment',data) //异步执行完,触发mutations中方法的执行
}
}
})
//main.js
import store from './store/index'
//Vue.prototype.$store = store
//store可以注册在原型上,也可以注册在跟实例上
const app = new Vue({
...App,
store,
})
state
- 对于当前页面只使用一个store中的变量,并且当前页面不会改变state中使用到的数据,则可以直接
{{$store.state.name}}
- 对于当前页面需要使用多个state中的数据或者当前页面会操作vuex中数据的改变,则需要在计算属性computed中使用state的辅助函数 mapState,实时监测state的改变,实时更新页面
使用方法
//引入:
import { mapState } from 'vuex'
computed:{
//这里使用...的意思是对象的扩展,用于和其他的计算变量合并成一个对象
...mapState(['name','sex']), //数组形式,名字对应
...mapState({ //变量名可以不一致
name:'name',
sex:(state) => state.userinfo.sex
})
}
getters
- getters可以作为其他getters方法的参数
getters: {
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
- 同state一样,页面使用getters方法返回的包装数据也分为两种情况
this.$store.getters.doneTodosCount
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
//或对象
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
mutations
- 调用 this.$store.commit(‘increment’, 参数)
- 必须是同步函数
import { mapMutations } from 'vuex'
export default {
// 这里仅仅是把方法注册进来,相当于只定义了方法,在合适的时机再去调用this.add(参数),并且传参
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
action
- Action 类似于 mutation,操作数据
- Action 提交的是 mutation,而不是直接变更状态
- Action 可以包含任意异步操作
actions
- 普通使用:this.$store.dispatch(‘xxx’,data)
import { mapActions } from 'vuex'
export default {
// 这里仅仅是把方法注册进来,相当于只定义了方法,在合适的时机再去调用this.add(参数),并且传参
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为`this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}