vuex的使用

使用Vuex统一管理状态的好处

  1. 能够在vuex中集中管理共享的数据,易于开发和后期的维护
  2. 能够高效的实现组件之间的数据共享,提高开发效率

Vuex的基本使用

  1. 安装vuex依赖包
    npm install vuex --save
  2. 导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
  1. 创建store对象
const store = new Vuex.Store({
      // state   中存放全局共享的数据
      state:{},
      // mutations 存放着全局共享的方法
      mutations:{},
      // actions 异步任务时携带参数
      actions:{
            addNAsync(context, step){
                        setTimeout(() => {context.commit('addN', step)},1000 )
                  }
            },
      // getter 可以对store中已有加工处理形成的新数据,类型于vue的计算属性
      // store中的数据进行改变,getter中的数据也会跟着变化
      getters:{
                  showNum:state => { 
                              return '当前最新的数量是[' + state.属性 + ']'
                        }
            }

})
  1. 将store对象挂载到 vue 实例中
var vm = new Vue({
      el:'#app',
      data:{},
      methods:{},
      store
})

5.调用mutations中的方法

var vm = new Vue({
      el:"#app",
      data:{},
      methods:{
            // 调用mutations中的方法
            f1:function(){
            this.$store.commit("函数名")
            },
            // 调用mutations中的方法带参数
            f2:function(){
            this.$store.commit("函数名",参数1)
            }
      }
})

5.调用mutations中的方法 第二种方式

// 从vuex 中按需导入mapMutations 函数
import [mapMutations] from 'vuex'
// 通过岗前导入的mapMutations函数将需要的mutations函数,映射为当前组件的methos方法
methods : {
      ...mapMutations(['add', 'addN'])
}
  1. 调用Action中的方法
// 触发Action方法
methods:{
           f1:function(){
                  // 在调用 dispatch 函数,触发action
                        this.$action.dispatch('函数', 5)
                  }
      }
  1. 调用Action中的方法 方式二
// 1.从vuex中按需导入 mapActions 函数
import [ mapActions ] from 'vuex'
// 2.将指定的 action 中的函数,映射为当前组件的methods方法
methods : {
            ...mapActions(['函数1', '函数2'])
      }
  1. 调用getter中的方法
      方式1
      this.$store.getters.函数名
      方式二
      import { mapGetters } from 'vuex'
      
      computed:{
      ...mapGetters(['函数1', '函数2'])
      }
posted @ 2020-12-04 18:02  萌新_python  阅读(105)  评论(0)    收藏  举报