zoukankan      html  css  js  c++  java
  • vuex

    store 文件夹下的 index.js 

     1 import Vue from 'vue'
     2 import Vuex from 'vuex'
     3  
     4 Vue.use(Vuex);
     5  
     6 // 创建实例 并导出
     7 export default new Vuex.Store({
     8     state: {
     9         count: 1
    10     },
    11     getters: { // 监听 依赖的的值变化,会重新计算  类似vue的computed
    12         getStateCount: function (state) { // 上面的state
    13             return state.count + 1
    14         }
    15     },
    16     mutations: { // 修改count值  提交mutation来修改  +1  -1
    17         add(state,n){
    18             state.count = state.count+n;
    19         },
    20         reduction(state){
    21             state.count = state.count-1;
    22         }
    23     },
    24     actions: { // 注册actions 类似vue里的methods  在actions中提交mutation再去修改状态值
    25         addFun(context,n) {
    26             context.commit("add",n)
    27         },
    28         reductionFun(context){
    29             context.commit("reduction")
    30         }
    31     },
    32     modules: {} // 多文件状态管理
    33 })

    HelloWorld.vue

    <template>
        <div class="hello">
            <h1>{{ this.$store.state.count }}</h1>
            <h1>{{ this.$store.getters.getStateCount }}</h1>
     
            <p>count的值:{{this.$store.state.count}}</p>
            <button @click="addFun">+</button>
            <button @click="reductionFun">-</button>
     
            <div style="border:1px solid pink; margin-top: 50px">{{count1}}</div>
        </div>
    </template>
     
    <script>
        // import {mapState, mapActions, mapGetters} from 'vuex'
        import {mapState} from 'vuex'
     
        export default {
            name: 'HelloWorld',
            props: {
                msg: String
            },
     
     
            computed: {
                ...mapState({
                    count1: state => state.count
                })
            },
            methods: {
                // addFun() {
                //     this.$store.commit("add")
                // },
                // reductionFun(){
                //     this.$store.commit("reduction")
                // }
     
                addFun() {
                    this.$store.dispatch("addFun", 10);
                },
                reductionFun() {
                    this.$store.dispatch("reductionFun")
                }
            },
        }
    </script>
     
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped lang="less">
    </style>

  • 相关阅读:
    读《构建之法》8、9、10章有感
    评论
    复利计算器(4)——jQuery界面美化、自动补全
    送给搭档的“汉堡”
    MFC之TreeCtrl控件使用经验总结
    MFC绘制图片闪烁详解
    MFC 网络编程中::connect返回-1问题
    C++网络编程之select
    C++关于Condition Variable
    Mutex 和 Lock
  • 原文地址:https://www.cnblogs.com/xiaozhu-zhu/p/11946912.html
Copyright © 2011-2022 走看看