vuexの簡単な使用


1、インストール
npm install vuex --save

2、簡単な例
(1)src/vuex/store.jsに次のコードを書き込みます.
//   vue
import Vue from 'vue'
//   vuex
import Vuex from 'vuex'

//   vuex
Vue.use(Vuex)


// 1、state:       


const state = {
    //       
    count: 1
}


// 2、mutations:         


const mutations = {
    //       -    
    ADD (state, n) {
        state.count += n;
    }
}


// 3、getters:      state


const getters = {
    count: function(state){
        return state.count;
    }
}


// 4、actions:        mutations


const actions ={
    //   mutations      -    
    add ({commit}, data) {
        commit('ADD', data)
    }
}
// 5、    Store 


const store = new Vuex.Store({
    state,
    mutations,
    getters,
    actions
});

// 6、  store
export default store;

コードの説明:
state-mutations-getters-actions-store、以上の書き方は基本的に固定されています.スモールプロジェクトは上の簡単な管理状態でOKです.(2)src/main.jsコード
import Vue from 'vue'
import App from './App'
import router from './router'
//   store
import store from './vuex/store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, //     
  components: { App },
  template: ''
})

(3)src/compontent/Count.vueページコンポーネントのコードは次のとおりです.
template>
    div class="hello">
        h1>{{ msg }}</h1>
        h2>{{count}}</h2>
        button @click="clickAdd">  /button>
    /div>
/template>
<script>
export default {
    data () {
        return {
            msg: 'Vuex test!'
        }
    },
    computed: {
        //   state 
        count() {
            return this.$store.state.count;
        }
    },
    methods: {
        clickAdd() {
            //  action  add  
            this.$store.dispatch('add', 1);
        }
    }
}
/script>
style scoped>

/style>