vuex mapMutations 使用

你能够在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(须要在根节点注入 store)。css

import Vue from 'vue'; import Element from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import App from './App'; import router from './router'; import Vuex from 'vuex'; Vue.config.productionTip = false; Vue.use(Vuex); Vue.use(Element) //vuex的配置 //注意Store是大写
const store = new Vuex.Store({ //数据保存
 state: { show: false, count: 0, list: [1, 5, 8, 10, 30, 50] }, mutations: { increase(state, n = 1) { state.count += n; }, decrease(state, n = 1) { state.count -= n; }, switch_dialog(state) { // 这里的state对应着上面这个state
            state.show = state.show ? false : true
            // 你还能够在这里执行其余的操做改变state
 } }, getters: { filteredList: state => { return state.list.filter(item => item < 31); } }, actions: { asyncIncrease(context) { context.commit('increase'); }, switch_dialog123(context) { // 这里的context和咱们使用的$store拥有相同的对象和方法
            context.commit('switch_dialog') // 你还能够在这里触发其余的mutations方法
 } } }); /* eslint-disable no-new */
new Vue({ el: '#app', router, //使用vuex
 store: store, render: h => h(App), });
<template>
    <div> {{count}} <button @click="handleIncrease">+5</button>
        <button @click="handleDecrease">-5</button> {{filteredList}}
        <button @click="handleRouter">跳转到 HelloWorld3</button>
        <button @click="showRouter">展现路由</button>
    </div>
</template>

<script> import { mapState } from 'vuex' import { mapGetters } from 'vuex' import { mapMutations } from 'vuex' export default { name: 'HelloWorld2', computed: { // count(){
            // return this.$store.state.count;
            // },
            // filteredList() {
            // return this.$store.getters.filteredList;
            // },
 ...mapState({ count: state => state.count }), // 使用对象展开运算符将 getter 混入 computed 对象中
 ...mapGetters([ 'filteredList' ]) }, methods: { handleIncrease() { // this.$store.commit('increase', 5);
                this.increase(); }, handleDecrease() { this.$store.commit('decrease', 5); }, handleAsyncIncrease() { this.$store.dispatch('asyncIncrease'); }, handleRouter() { this.$router.push('/HelloWorld3'); }, showRouter() { console.log(this.$router); console.log(this.$router.push); }, //mapMutations 使用方法一 // ...mapMutations([ // 'increase', // 将 `this.increase()` 映射为 `this.$store.commit('increase')` // ]), //mapMutations 使用方法二  ...mapMutations({ increase: 'increase'// 将 `this.increase()` 映射为 `this.$store.commit('increase')`  }) } }; </script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
相关文章
相关标签/搜索