zoukankan      html  css  js  c++  java
  • vuex的简单使用

    使用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>

  • 相关阅读:
    【Henu ACM Round#17 A】Simple Game
    【Henu ACM Round #12 E】Thief in a Shop
    【Henu ACM Round#16 D】Bear and Two Paths
    【Henu ACM Round#16 A】 Bear and Game
    P4824 [USACO15FEB]Censoring (Silver) 审查(银)
    P4001 [BJOI2006]狼抓兔子
    P2444 [POI2000]病毒
    P3966 [TJOI2013]单词
    P3796 【模板】AC自动机
    P4574 [CQOI2013]二进制A+B
  • 原文地址:https://www.cnblogs.com/yesyes/p/6659292.html
Copyright © 2011-2022 走看看