Vuex 基础

2020-02-24  本文已影响0人  BestFei

零、场景说明
通过vuex实现计数器的功能

一、入口文件进入vuex
import Vuex from 'vuex'

Vue.use(Vuex)
二、入口文件修改

new一个vuex的Store实例,初始 state 状态对象

const store = new Vuex.Store({
  state: {
    count: 0,
  }
})

在vue中注入store,为了在每个实例中可以通过this.$store来访问

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')
三、在页面访问count的值

修改app.vue文件

<template>
  <div id="app">
    {{count}}
  </div>
</template>

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

此时,页面已经能展示count的值了


四、实现动态变化的功能

1、在页面上增加一个按钮,实现点击后count值加一的效果

<button @click="$store.commit('increment')">count++</button>

2、修改入口
在申明的Store代码中增加一个mutations方法increment,与页面上的点击时间触发的方法名一致

const store = new Vuex.Store({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

此时,页面已经实现了通过点击【count++】按钮来count的值加一的效果。


3、同理如果我们要实现一个加二的操作
修改按钮

<button @click="$store.commit('increment2',2)">count+2</button>

修改mutations

mutations: {
    increment2(state,n) {
      state.count +=n
    }
  }
五、actions实现异步操作

actions通过 commit 的形式提交给 mutations 去处理

actions: {
    dispatch_increment({commit}) {
      setTimeout(()=>{
        commit('increment')
      }, 3000)
    }
  }

页面添加一个按钮,通过dispatch来调用actions

<button @click="$store.dispatch('dispatch_increment')">count++ by dispatch</button>

这样就实现了,通过点击【count++ by dispatch】来实现延迟3秒,count值加一的效果了。

六、缓存数据

vuex的getters有点类似于计算属性,可以用来缓存数据

getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }

修改页面,增加页面调用

{{$store.getters.doubleCount}}

这样就实现了,点击按钮后,值扩大两倍的效果了


七、总结

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

上一篇下一篇

猜你喜欢

热点阅读