初学Vuex

2018-03-03  本文已影响10人  汪槑槑2017

Vuex 是什么?(https://vuex.vuejs.org/zh-cn/intro.html)

官方文档!!!必须深入理解

1. what is it?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

2. why


3. Use 

1.  src 下新建store.js

import Vue from 'vue';

import Vuex from 'vuex';

Vue.use(Vuex);

const state= {

    count: 0 

};

const mutations={

    INCREMENT(state){

        state.count++;

    },

    EVENADD(state) {

        state.count+=2;

    }

};

const actions={

    increment({commit}){

        // ajax,promise

        setTimeout(() => {

            commit('INCREMENT');

        },1500)

    },

    evenadd({commit,state}){

        if( state.count%2 === 0) {

            commit('EVENADD')

        }else{

            console.log('数字不合法!')

        }

    }

};

const getters={

    c(state){

        return state.count;

    }

}

export default new Vuex.Store({

    state,

    getters,

    mutations,

    actions

}) 

2. 在main.js中 import store 

import Vue from 'vue'

import App from './App'

import store from './store'

// Vue.config.productionTip = false

/* eslint-disable no-new */

new Vue({

  el: '#app',

  store,

  components: { App },

  template: ''

})

3.  App.vue

<template>

    <div  id="app">

        <h3>Welcome vue </h3>

        <input type="button" value="add" @click="increment">

        <input type="button" value="evenadd" @click="evenadd">

        <div>{{ c }}</div>

    </div>

</template>

<script>

  import { mapGetters,mapActions } from 'Vuex';

  export default{

    // methods:{

    //  increment(){

    //    // alert(1)

    //    this.$store.dispatch('increment');

    //  },

    //  evenadd(){

    //    this.$store.dispatch('evenadd');

    //  }

    // }

    methods:mapActions([

      'increment',

      'evenadd'

    ]),

    computed: mapGetters([

      'c'

    ])

  }

</script>

上一篇 下一篇

猜你喜欢

热点阅读