首页 > 解决方案 > Vue:当数据异步更改时 Radio 不会更新其值

问题描述

我不明白为什么我的新代码不起作用。我能够提取一个最小的可重现案例。当created()同步设置数据时,效果很好,并显示文章收音机。当我用超时包围它时,博客将保持选中状态。Vue 2.6.12

此代码中的错误已修复,但这不是我麻烦的原因,因为我的真实代码不同。我的问题是,在更改反应数据之后,未选中单选按钮。

<Radio
  v-model="type"
  identifier="article"
  class="pl-3"
  label="article"
  name="type"
/>
<Radio
  v-model="type"
  identifier="blog"
  class="pl-3"
  label="blog"
  name="type"
/>
<div>Selected {{ type }}</div>

  data() {
    return {
      type: "blog",
    };
  },
  created() {
    setTimeout(function () {
      this.type = "article";
      console.log(this.type);
    }, 800);
  },

这让我大吃一惊,因为不同组件中的类似代码运行良好。

更新:

我的原始代码不起作用,是

computed: {
  blog() {
    return this.$store.getters.BLOG;
  },
},
watch: {
 blog() {
  this.type = (this.blog.info.editorial) ? 'article' : 'blog';
 },

created() {
  this.$store.dispatch('FETCH_BLOG', { slug: this.slug });
},

相关源代码:

标签: javascriptvue.js

解决方案


您只需将函数更改为箭头函数,因为它不会像这样指向您的数据

setTimeout(() => {
      this.type = "article";
      console.log(this.type);
}, 800);

推荐阅读