vue-cli简单使用vuex

版权声明:本文为博主原创文章,非商业转载请附上地址与作者信息,谢谢! https://blog.csdn.net/jx950915/article/details/81563228

下载

npm install vuex --save

使用

  • 新建一个文件夹(javascript
  • 新建一个文件(store.js

store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increase(state) {
            state.count++
        },
        subtract(state){
            state.count--
        }
    },
     // 注册一个简单的 action
    actions: {
        actionIncrease({
            commit
        }) {
            commit('increase')
        },
        actionSubtract({
            commit
        }) {
            commit('subtract')
        }
    }
})
export default store

main.js

import  store from "./javascript/store"; //引入store

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store, //加入store对象
    components: {
        App
    },
    template: '<App/>'
})

vue

<template>
    <div id="vuex">
        <button @click="subtract">-</button>
        {{count}}
        <button @click="add">+</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                // count:store.state.count
            };
        },
        computed: {
            count() {
                return this.$store.state.count;
            }
        },
        methods: {
            // 分发 Action
            add() {
                this.$store.dispatch('actionIncrease')
            },
            subtract() {
                this.$store.dispatch('actionSubtract')
            }
        }
    };
</script>

效果

1

猜你喜欢

转载自blog.csdn.net/jx950915/article/details/81563228