Live2d Test Env

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>

 

posted @ 2019-11-28 09:22  小猪(朱)  阅读(191)  评论(0编辑  收藏  举报