【问题标题】:Set value of data in vue component from external api call通过外部 api 调用设置 vue 组件中数据的值
【发布时间】:2020-10-31 05:36:16
【问题描述】:

我想从 vuex 存储中设置组件内数据变量的初始状态。

但是,我通过 api 调用从组件更新 vuex 存储,以确保数据是最新的。

所以在我的组件中,我有以下启动更新的内容

    created: function () {
        uibuilder.send('getSchedules')
    },

消息从我的 API 返回,并在我的主 index.js 中提取:

this.$store.commit('schedules/SAVE_SCHEDULES', newVal.payload);

并且更新通过 store.js 中的突变发生

    SAVE_SCHEDULES(state, schedules) {
        state.schedules = schedules;
    },

提取的数据将用于填充组件中文本框的初始值。我以为我可以设置一个计算属性来访问处于 vuex 状态的对象

    computed: {
        schedule() {
            return this.$store.getters['schedules/getScheduleByName'](this.picked);
        },
    },

然后使用计算对象中的值设置数据对象。

    data() {
        return {
            picked: 'shd-1',
            tag: this.schedule.tag
        }
    },

然后我可以使用 v-model 来跟踪文本框值的变化。

<input type="text" id="shd-tag" class="mb-2" v-model="tag">

但是,无论我将 API 调用放在组件生命周期中的哪个位置,我都会收到未定义值错误:

Error in data(): "TypeError: Cannot read property 'tag' of undefined"

在我尝试在数据定义中访问它之前,vuex 存储似乎没有更新。请问有谁知道我该如何实现这一目标?

谢谢,

马丁

【问题讨论】:

  • this.picked,你作为参数发送给你的getter,是什么?不在组件 data() 声明中,你是作为 prop 传递的吗?
  • 抱歉,我一定是错过了。我现在已将其添加到问题中。
  • 最有可能的是,当组件挂载您的 http 请求时尚未满足,因此,因为您正在调用尚未创建的对象的属性,您会收到错误消息。一般来说,你的逻辑对我来说没有多大意义,如果你有一个返回整个对象的计算,你真的不需要将它添加到 data() 中,如果你真的想访问 tag 的属性返回对象也为此创建一个计算对象,并在其中放置一个逻辑来检查对象是否被实例化。

标签: vue.js vuex


【解决方案1】:

对于 cmets,声明一个响应式字符串,来自一个通过 http 调用实例化的对象并不是最好的解决方案。当你的组件被挂载时,http 请求很可能还没有完成。

为了简化,您可以将计算结果更改为:

computed: {
    schedule() {
        return this.$store.getters['schedules/getScheduleByName'](this.picked);
    },
    //this will return the tag if present, or an empty string
    tag() {
      return (this.schedule.tag) ? this.schedule.tag : "";
    }
},

并从 data() 中删除标签

    return {
        picked: 'shd-1',
         //now instead of the tag declared here,
         //you can call your computed property tag in the same exact way
    }

【讨论】:

  • 啊,谢谢。我没有意识到我可以将计算属性分配给 v-model。这意味着我摆脱了数据中的标签,只需获取计划对象并使用它的属性!我的误解。再次感谢
  • 没问题。如果您在 v-model 中使用计算,请查看 vue 文档中的计算属性设置器和获取器!享受编码
  • 会的。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2019-06-12
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 2019-05-25
  • 2020-06-09
相关资源
最近更新 更多