[Vue基础实战]Vuex演练

参考代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vuex Demo</title>    
</head>
<body>    
    <div id="app">
      <amount></amount>
      <counter></counter>
    </div>
    <template id="amount">
        <div style="background-color: lightblue;">
            <h3>{{$store.getters.optCount}}</h3>           
        </div>
    </template>
    <template id="counter">
        <div style="background-color: lightcoral;">
           <input type="button" value="减少" @click="remove">
           <input type="button" value="增加" @click="add">  
           <br>
           <input type="text" v-model="$store.state.count">        
        </div>
    </template>
    <script src="../js/vue.js"></script>
    <script src="../node_modules/vuex/dist/vuex.js"></script>        
    <script>  
       
        var store=new Vuex.Store({
            state:{
                count:0
            },
            mutations:{
                increment(state){
                    state.count++;
                },
                subtract(state,obj){
                    state.count-=(obj.val);
                }
            },
            getters:{
                optCount:function(state){
                    return '当前最新的count值是:'+state.count;
                }
            } 
        });  
        Vue.component('amount',{
            template: '#amount'
        });
        Vue.component('counter',{
            template: '#counter',
            data() {
                return {};
            },
            methods: {
                add() {
                    this.$store.commit('increment');                    
                },
                remove(){
                    this.$store.commit('subtract',{val:1});
                }
            },
        });  
        var wm = new Vue({
            el: '#app',
            data:{},
            store
        });
    </script>
</body>
</html>

 

posted @ 2021-01-14 17:47  dshow  阅读(88)  评论(0编辑  收藏  举报