vuex的用法及介绍

使用:

主要使用场景是适合大型单页面

  • 仓库store包含了应用的数据(状态)和操作过程,任何组件使用同一store的数据,只要store的数据变化,对应的组件也会立即更新
  • 数据保存在Vuex的state字段内,任何页面组件都可以通过$store.state.变量名称去读取数据
  • 修改state数据,显示地提交mutations,使用this.$store.commit方法来执行mutations,例如,mutations里面的方法可以设置第二个参数,第二个参数可以设置默认值,也可以传入参数
  • “getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,有时候某个数据是计算之后获取的数据,用getter减少代码冗余
  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
  • Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters

具体操作实例可以看如下代码

  • 使用vuex需要先在main.js中引入,具体可看我的另一篇关于main.js设置的博文

https://blog.csdn.net/weixin_44258964/article/details/105835057

vuex的配置

//vuex/store.js文件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  name: 'yan',
  age: 23,
  obj: [{ bookname: '荒诞', num: 20 }, { bookname: '行为学', num: 30 }, { bookname: '荒诞行为学', num: 40 }]
}
const mutations = {
  changename (state, name) {
    state.name = name
  },
  changeage (state) {
    state.age++
  }
}
//需要统一设置的变量可在此设置
const getters = {
  checkObj (state) {
    return state.obj.filter(res => { return res.num > 25 })
  }
}
// 异步不是很理解如何运用
const actions = {
  changeage (context) {
    context.commit('changeage')
  }
}

const store = new Vuex.Store({
  //  vuex的配置
  state, mutations, getters, actions
})

export default store

vuex的应用

//使用文件
changName () {
      // vuex通过commit提交修改
      this.$store.commit('changename', 'yanjiazhen')
      this.$store.commit('changeage')
      // getter获取计算内容
      this.obj = this.$store.getters.checkObj
}

缺点:页面刷新会导致数据丢失

错误解决

控制台报错TypeError: WEBPACK_IMPORTED_MODULE_1_vuex.a.store is not a constructor
TypeError: “x” is not a constructor
解决:创建Vuex实例的时候,Store需要大写 new Vuex.Store

原创文章 19 获赞 16 访问量 1156

猜你喜欢

转载自blog.csdn.net/weixin_44258964/article/details/105853865