目录
Vue全家桶之vuex

Vuex是一个专为Vue.js应用程序开发的状态管理模式,用于解决不同组件的数据共享,数据持久化。


  1. 安装
    npm install vuex

  2. 引用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    // src下创建vuex文件夹,vuex下创建store.js文件
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)

    // 实例化 Vuex.store
    const store = new Vuex.Store({
    // state 定义存储数据
    state: {
    count: 1
    },

    // mutation 定义方法,用于改变state里面的数据
    mutations: {
    increment (state) {
    state.count++
    }
    }

    // getters 改变state里的数据会自动触发getters里的方法
    getters: {
    computedCount: (state) => {
    return state.count*2
    }
    }

    // action 提交的是mutation,而不是直接变更状态,可以包含任意异步操作。
    actions: {
    increment (context) {
    context.commit('increment')
    }
    }
    })

    // 暴露 store
    export default store
  3. 使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // 引入 store
    import store from '../vuex/store.js'

    // 注册
    export default{
    store,
    methods(){
    count(){
    // 触发mutation里的方法,改变数据
    this.$store.commit('increment')
    // 触发action里的方法
    this.$store.dispatch('increment')
    }
    }
    }

    // 获取数据
    <div>{{this.$store.state.count}}</div>

文章作者: Hyman Choi
文章链接: http://yoursite.com/2019/06/18/Vue全家桶之vuex/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 凌晨四点的拖拉机