admin管理员组

文章数量:1794759

Vuex

Vuex

原文网址:Vuex--mutations--使用/教程/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

本文用示例介绍Vuex的五大核心之一:mutations。

官网

Mutation | Vuex

API 参考 | Vuex

mutations概述

        mutations是vuex里唯一可以改变state数据的方法。

        有多个对象,里边包含多个直接更新 state 的方法(回调函数)

        触发方式: action 中的 commit(‘mutation 名称’)

        只能包含同步代码, 不能写异步代码。

用法

直接使用

//在JS中使用
this.$storemit('mutations方法名', 具体值)        // 不分模块
this.$storemit('模块名/mutations方法名', 具体值) // 分模块//在模板中使用
$storemit('mutations方法名', 具体值)        // 不分模块
$storemit('模块名/mutations方法名', 具体值) // 分模块

mapMutations

import { mapMutations } from 'vuex'
export default {computed: {// 不分模块...mapMutations(['mutations方法名'])// 分模块,不修改方法名...mapMutations('模块名', ['mutations方法名'])// 不分模块,不修改方法名...mapMutations('模块名', {'新mutation方法名': 'mutation方法名'})}
}

示例

CounterStore.js

import Vue from 'vue';
import Vuex from 'vuex';Vue.use(Vuex);
const counterStore = new Vuex.Store({state: {count: 10},getters: {doubleCount(state) {return state.count * 2;}},mutations: {increment(state) {state.count++;},decrement(state) {state.count--;},// 带参数addNumber(state, param1) {state.count += param1;},},}
);export default counterStore;

Parent.vue(父组件,是个入口组件)

<template><div class="outer"><h3>父组件</h3><component-a></component-a><component-b></component-b></div>
</template><script>
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";export default {name: 'Parent',components: {ComponentA, ComponentB},
}
</script><style scoped>
.outer {margin: 20px;border: 2px solid red;padding: 20px;
}
</style>

ComponentA.vue(改变vuex的数据)

<template><div class="container"><h3>ComponentA</h3><button @click="thisIncrement">加1</button><button @click="thisDecrement">减1</button><button @click="thisAddNumber">增加指定的数</button></div>
</template><script>
export default {data() {return {cnt: 5}},methods:{thisIncrement() {this.$storemit('increment')},thisDecrement() {this.$storemit('decrement')},thisAddNumber() {this.$storemit('addNumber', thist)}}
}
</script><style scoped>
.container {margin: 20px;border: 2px solid blue;padding: 20px;
}
</style>

ComponentB.vue(读取vuex的数据) 

<template><div class="container"><h3>ComponentB</h3><div>计数器的值:{{thisCount}}</div><div>计数器的2倍:{{thisDoubleCount}}</div></div>
</template><script>
export default {computed:{thisCount() {return this.$store.state.count;},thisDoubleCount() {return this.$store.getters.doubleCount;},}
}
</script><style scoped>
.container {margin: 20px;border: 2px solid blue;padding: 20px;
}
</style>

 路由(router/index.js)

import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";Vue.use(Router)export default new Router({routes: [{path: '/parent',name: 'Parent',component: Parent,}],
})

测试

访问:http://localhost:8080/#/parent

本文标签: vuex