初学Vuex

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>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 7,990评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,299评论 0 6
  • Vuex 的学习记录 资料参考网址Vuex中文官网Vuex项目结构示例 -- 购物车Vuex 通俗版教程Nuxt....
    流云012阅读 5,316评论 0 7
  • State 单一状态树 Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“...
    peng凯阅读 3,945评论 2 0
  • import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(V...
    F_imok阅读 7,432评论 0 12