标签:奇数 事件触发 port click action use add 管理 函数
使用vuex进行组件间数据的管理
npm i vuex -S
main.js
import Vue from ‘vue‘ import App from ‘./App.vue‘ import store from ‘./store.js‘ new Vue({ store, el: ‘#app‘, render: h => h(App) })
store.js
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex) // 这里定义初始值 let state = { count:10 }; const mutations = { add(context){ context.count++ }, decrease(context){ context.count-- } }; // 事件触发后的逻辑操作 // 参数为事件函数 const actions = { add(add){ add.commit(‘add‘) }, decrease(decrease){ decrease.commit(‘decrease‘) }, oddAdd({commit,state}){ if (state.count % 2 === 0) { commit(‘add‘) } } }; // 返回改变后的数值 const getters = { count(context){ return context.count }, getOdd(context) { return context.count % 2 === 0 ? ‘偶数‘ : ‘奇数‘ } }; export default new Vuex.Store({ state, mutations, actions, getters })
App.vue
<template>
  <div id="app">
  <button @click="add">add</button>
  <button @click="decrease">decrease</button>
  <button @click="oddAdd">oddAdd</button>
  <div>{{count}}</div>
  <div>{{getOdd}}</div>
  </div>
</template>
<script>
import {mapGetters,mapActions} from ‘vuex‘
    export default {
        // 得到计算后的值
        computed:mapGetters([‘count‘,‘getOdd‘]),
        // 发生点击事件触发不同函数
        methods:mapActions([‘add‘,‘decrease‘,‘oddAdd‘])
    }
</script>

标签:奇数 事件触发 port click action use add 管理 函数
原文地址:http://www.cnblogs.com/yesyes/p/6659292.html