(七)vuexの使用

3655 ワード

Vuexは、グローバルデータを格納し、コンポーネント間のデータ転送を管理するために使用されます.1.インストール
npm install --save vuex

2.参照
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)
import store from './store'
new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

3.vuexには4つのコア機能があります:state mutations getters actions
    var myStore =  new Vuex.Store({           //  vuex   。
        state:{
            //           
            name:"jjk"
        },
         mutations:{
             //     state    
         },
         getters:{
             //       
         },
         actions:{
             //
         }
    });
    new Vue({
        el:"#app",
        data:{name:"jjk"},
        store:myStore,
        mounted:function(){
            console.log(this)//   
        }
    })

4.demoと書いてあります.コードは以下の通りです.
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

export default  new Vuex.Store({
    state: {
        count:0
    },
    mutations: {
        INCREMENT(state) {
            state.count++;
        },
        DECREMENT(state) {
            state.count--
        },
        INCREMENT_WITH_VALUE(state, value){
            state.count +=value;
        }
    },
    getters:{
        show_value(state){//   state       state
            return state.count;
        }
    },
    actions: {
        increment(context){
            context.commit("INCREMENT")
        },
        decrement({commit}){
            commit("DECREMENT")
        },
        incrementWithValue({commit}, value){
            commit("INCREMENT_WITH_VALUE",  parseInt(value))
        }
    }
})
//   ,  
// increment({commit}){
//     commit("INCREMENT")
// },
 



    import { mapState, mapGetters, mapMutations,mapActions } from 'vuex'
    export default {
        data() {
            return {
                incrementValue: 0
            }
        },
        computed:{
            ...mapGetters(['show_value']),
        },
        methods: {
            ...mapActions(["increment","decrement"]),
            incrementWithValue() {
                this.$store.dispatch("incrementWithValue", this.incrementValue)
            }
        }
    }




    export default {
        data() {
            return {
                incrementValue: 0
            }
        },
        computed:{
            show_value(){
                return this.$store.state.count;
            }
        },
        methods: {
            increment(){
                this.$store.dispatch("increment")
            },
            decrement(){
                this.$store.dispatch("decrement")
            },
            incrementWithValue() {
                this.$store.dispatch("incrementWithValue", this.incrementValue)
            }
        }
    }