一、 Getter
我们先回忆一下上一篇的代码
computed:{
  getName(){
   return this.$store.state.name
  }
}
这里假设现在逻辑有变,我们最终期望得到的数据(getName),是基于 this.$store.state.name 上经过复杂计算得来的,刚好这个getName要在好多个地方使用,那么我们就得复制好几份.
vuex 给我们提供了 getter,请看代码 (文件位置 /src/store/index.js)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
 // 类似 vue 的 data
 state: {
  name: 'oldName'
 },
 // 类似 vue 的 computed -----------------以下5行为新增
 getters:{
  getReverseName: state => {
    return state.name.split('').reverse().join('')
  }
 },
 // 类似 vue 里的 mothods(同步方法)
 mutations: {
  updateName (state) {
   state.name = 'newName'
  }
 }
})
然后我们可以这样用 文件位置 /src/main.js
computed:{
  getName(){
   return this.$store.getters.getReverseName
  }
}
事实上, getter 不止单单起到封装的作用,它还跟vue的computed属性一样,会缓存结果数据, 只有当依赖改变的时候,才要重新计算.
二、 actions和$dispatch
细心的你,一定发现我之前代码里 mutations 头上的注释了 类似 vue 里的 mothods(同步方法)
为什么要在 methods 后面备注是同步方法呢"htmlcode">
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
 // 类似 vue 的 data
 state: {
  name: 'oldName'
 },
 // 类似 vue 的 computed
 getters:{
  getReverseName: state => {
    return state.name.split('').reverse().join('')
  }
 },
 // 类似 vue 里的 mothods(同步方法)
 mutations: {
  updateName (state) {
   state.name = 'newName'
  }
 },
 // 类似 vue 里的 mothods(异步方法) -------- 以下7行为新增
 actions: {
  updateNameAsync ({ commit }) {
   setTimeout(() => {
    commit('updateName')
   }, 1000)
  }
 }
})
然后我们可以再我们的vue页面里面这样使用
methods: {
  rename () {
    this.$store.dispatch('updateNameAsync')
  }
}
三、 Module 模块化
当项目越来越大的时候,单个 store 文件,肯定不是我们想要的, 所以就有了模块化. 假设 src/store 目录下有这2个文件
moduleA.js
export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}
moduleB.js
export default {
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}
那么我们可以把 index.js 改成这样
import moduleA from './moduleA'
import moduleB from './moduleB'
export default new Vuex.Store({
  modules: {
    moduleA,
    moduleB
  }
})
这样我们就可以很轻松的把一个store拆分成多个.
四、 总结
- actions 的参数是 store 对象,而 getters 和 mutations 的参数是 state .
- actions 和 mutations 还可以传第二个参数,具体看vuex官方文档
- getters/mutations/actions 都有对应的map,如: mapGetters , 具体看vuex官方文档
- 模块内部如果怕有命名冲突的话,可以使用命名空间, 具体看vuex官方文档
- vuex 其实跟 vue 非常像,有data(state),methods(mutations,actions),computed(getters),还能模块化.
vuex进阶
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
 
                        