vuex 让 store 通天

为了让 子组件 不用时刻引用 store文件

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex); //必须用Vue.use()来安装
const store = new Vuex.Store({
    //这里的state必须是JSON,是一个对象。
    state: {
        count: 0         //这里就是初始值的罗列
    },
    //突变,罗列所有可能改变state的方法
    mutations: {
        //没有所谓的大写字母的Type了,就是一个一个函数
        add (state) {
              state.count++;
        },
        minus (state) {
            state.count--;
        }
    }
});

export default store;

main.js:

import Vue from "vue";
import Vuex from "vuex";
import MyCompo from "./MyCompo.vue";


import store from "./store.js";

new Vue({
    el : "#app",
    store,
    data : {
        a : 100
    },
    render: h => h(App)
});

.vue组件文件中,使用this.$store来表示使用的那个全局store

<style scopoed>
 
</style>

<template>
    <div>
        我是子组件
        <h1>
            <button v-on:click="minusnandler">减少</button>
            {{count}}
            <button v-on:click="addhandler">增加</button>
        </h1>
    </div>
</template>

<script>
    export default {
        computed : {
            count(){
                return this.$store.state.count;
            }
        },
        methods : {
            addhandler(){
                this.$store.commit("add");
            },
            minusnandler(){
                this.$store.commit("minus");
            }
        }
    }
</script>

 

posted @ 2020-04-13 18:22  yun迹  阅读(156)  评论(0编辑  收藏  举报