【问题标题】:Vuex: Access object by keyVuex:按键访问对象
【发布时间】:2021-05-13 13:20:42
【问题描述】:

我有状态

bs: {
  page: 1,
  posts: {}
}

在这里,我正在存储带有突变的数据

state.bs.posts[Number(state.bs.page)] = posts // => posts array is coming from an http request

编辑:在这里我也尝试将其转换为 String(state.bs.page) 但没有得到所需的输出

所以每当我尝试使用 getter 访问时,例如

getBSPosts (state) {
    return (pageNo) => {
      return state.bs.posts[Number(pageNo)]
    }
}

现在,无论我想获取什么,getBSPosts 在组件/页面中返回 undefined。 它正在返回 __ob__ 观察者我如何获取名为 1 的键的值(在帖子对象中作为键的页码)

【问题讨论】:

    标签: nuxt.js vuex


    【解决方案1】:

    可以使用数字或字符串访问带有数字键的 JavaScript 对象,因此您无需担心对键进行类型转换。

    问题在于,由于 Vue 的 Object reactivity caveat,该属性没有被被动设置。在响应式对象上创建对象属性时必须使用Vue.set

    Vue导入商店:

    store.js

    import Vue from 'vue'
    

    并使用Vue.set设置对象数据:

    Vue.set(state.bs.posts, state.bs.page, posts);  // ✅ Correct
    
    state.bs.posts[Number(state.bs.page)] = posts;  // ❌ Incorrect
    

    【讨论】:

    猜你喜欢
    • 2020-12-05
    • 2020-05-18
    • 1970-01-01
    • 2018-07-15
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 2019-04-03
    相关资源
    最近更新 更多