一个简单的例子 vux mutation改变状态
D:\workspace\xxx\src\main.js
引用、注册、定义state、mutations
import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import Vuex from 'vuex' import Apple from '@/components/Apple' import Banana from '@/components/Banana' Vue.use(VueRouter) Vue.use(Vuex) let store = new Vuex.Store({ state: { totalPrice: 0 }, mutations: { increment (state, price) { state.totalPrice += price }, decrement (state, price) { state.totalPrice -= price } } }) let router = new VueRouter({ mode: 'history', routes: [ { path: '/apple', component: Apple }, { path: '/banana', component: Banana } ] }) /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
D:\workspace\xxx\src\App.vue
computed计算并呈现结果(show)
<template>
  <div id="app">
    <img src="./assets/logo.png">
    {{ totalPrice }}
    <Apple></Apple>
    <Banana></Banana>
  </div>
</template>
<script>
import Apple from './components/Apple'
import Banana from './components/Banana'
export default {
  components: { Apple, Banana },
  name: 'App',
  computed: {
    totalPrice () {
      return this.$store.state.totalPrice
    }
  }
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
D:\workspace\xxx\src\components\Apple.vue
调用mutations中的方法改变值(set)
<template>
    <div>
      <h1 >{{ msg }}</h1>
      <button @click="addOne">addOne</button>
      <button @click="minusOne">minusOne</button>
      <router-view/>
    </div>
</template>
<script>
export default {
  name: 'Apple',
  data () {
    return {
      msg: 'I am an apple',
      price: 5
    }
  },
  methods: {
    addOne () {
      this.$store.commit('increment', this.price)
    },
    minusOne () {
      this.$store.commit('decrement', this.price)
    }
  }
}
</script>
D:\workspace\xxx\src\components\Banana.vue
<template>
    <div>
      <h3 >{{ mg }}</h3>
      <button @click="addOne">addOne</button>
      <button @click="minusOne">minusOne</button>
    </div>
</template>
<script>
export default {
  name: 'Banana',
  data () {
    return {
      mg: 'I am a banana',
      price: 15
    }
  },
  methods: {
    addOne () {
      return this.$store.commit('increment', this.price)
    },
    minusOne () {
      return this.$store.commit('decrement', this.price)
    }
  }
}
</script>

下图可知,mutations扮演着改变状态的作用(同步)

下文
vux action改变状态
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号