vuex 练习
vuex
import Vue from 'vue'; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state:{ count:2, sum:100, orderList: { orderno: '1111' }, //订单列表 num:'' }, mutations:{ jia:(state,obj) => { //state.count+=str console.log(obj); state.count=obj.str1+obj.str2 }, jian:(state) => { state.count-- }, fun:(state,str) => { state.num=str }, someOtherMutation(state,str){ console.log(str) } }, actions:{//有异步功能 addAction(context,str){ //上下文对象,这里你可以理解称store本身。接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。 setTimeout(() => { context.commit('jia',str) },3000); console.log('我比jia提前执行'); }, reduceAction({commit}){ //直接把commit对象传递过来 console.log({commit}) commit('jian') }, someAction({commit},str){ console.log(str) return new Promise((resolve, reject) => { setTimeout(() => { // commit('someMutation') resolve() }, 1000) }) }, duogeAction({dispatch,commit}){ return dispatch('someAction',11).then(() => { commit('someOtherMutation',22) }) } }, //相当于计算属性 getters:{ // count:function(state){ // return state.count+=100; // } count:function(state){ return state.count; } } }) export default store;
-
src/.vue文件
`<template>` `<div >` ` 我是helloWord页面` `<ul>` ` <li><router-link :to="{path:'/home'}">home</router-link></li>` ` <li><router-link :to="{path:'/content'}">content</router-link></li>` `</ul>` `//////////////////////////////////////////////` ` <div>` ` <p>{{$store.state.count}}--{{count}}</p>` `<p>{{orderList.orderno}}</p>` ` <!--一个参数可以直接传,多个参数只能以对象或数组的方式一次传过-->` ` <button @click="$store.commit('jia',{'str1':3,'str2':4})">+++</button>` ` <button @click="jian">---</button>` ` <button @click='btn2'>改变store里的num 传值</button>` ` <p>{{num}}</p>` ` <p>full的值{{full}}</p>` //////////////////// ` <button @click='addAction("5")'>addAction 通过action触发mutation改变state</button>` ` <button @click='reduceAction'>reduceAction 通过action触发mutation改变state</button>` ` <button @click='duogeAction'>duogeAction 通过action触发action</button>` ` <button @click='btnChangeCoount'>btnChangeCoount </button>` ` </div>` ` </div>` ` </template>` ` <script>` //一系列的辅助函数 import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'; export default { name: '', data () { return { // count:0 full:'' } }, methods:{ btn2(){ var arr=[1,2,3] //多个参数以对象的方式传 this.$store.commit('fun',"33333") }, btnChangeCoount(){ this.reduceAction() }, ...mapMutations([ 'jian' ]), //用函数触发this.$store.dispatch('addAction'), ...mapActions([ 'addAction', 'reduceAction', 'duogeAction' ]) }, computed:{ ...mapState([ "count", "orderList", "num" ]), // count(){ // return this.$store.state.count // }, // orderList(){ // return this.$store.state.orderList // } //如果使用了getters ...mapGetters([ "count" ]) // count(){ // return this.$store.getters.count // } }, watch:{ count(val){ this.full=val; alert(1) } } } `</script>` `<style scoped>` `</style>`