Vue使用Vuex

时间:2020-05-01

安装插件

npm install vuex --save

新建store文件

app.js

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

Vue.use(Vuex);

const state = {
    number: 0
};

const mutations = {
    add(state) {
        state.number++;
    }
};

const actions = {
    add({commit}) {
        commit('add')
    }
};

const getters = {
    number1(state) {
        return state.number + 1;
    }
};

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

编辑App.vue文件代码

<template>
    <div id="app">
        {{$store.state.number}}

        <button @click="add">加1</button>

        <p>
            获取计算属性值:{{$store.getters.number1}}
        </p>
    </div>
</template>

<script>

    export default {
        name: 'App',
        methods: {
            add() {
                this.$store.dispatch('add');
            }
        }
    }
</script>

<style>

</style>

修改入口文件

main.js

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false;
import store from './store/app';

new Vue({
  render: h => h(App),
  store
}).$mount('#app');