vuex

安装vuex

cnpm install vuex

核心概念

  • State this.$store.state.xxx 取值,提供一个响应式数据
  • Getter this.$store.getters.xxx 取值,借助Vue的计算属性 computed 来实现缓存
  • Mutation this.$store.commit("xxx") 赋值,更改 state 方法
  • Action this.$store.dispatch("xxx") 赋值,触发 mutation 方法
  • Module Vue.set 动态添加state到响应式数据中

main.js

把store挂载到vue上

import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'

Vue.use(Vuex)
Vue.config.productionTip = false

const store = new Vuex.Store({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    increment({commit}) {
      // 模拟一个异步请求
      setTimeout(()=>{
        // state.count++
        // 不要对state进行更改操作,应该通过commit交给mutations去处理
        commit('increment')
      }, 3000)
    }
  },
  // 类似于计算属性的一个功能
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }
})

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

app.vue

<template>
  <div id="app">
    {{count}}
    <br>
    {{$store.getters.doubleCount}}
    <button @click="$store.commit('increment')">count++</button>
    <button @click="$store.dispatch('increment')">count++</button>
  </div>
</template>

<script>

export default {
  name: 'app',
  computed: {
    count() {
      return this.$store.state.count
    }
  }
}
</script>

results matching ""

    No results matching ""