微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue.js奇怪的反应性问题

如何解决Vue.js奇怪的反应性问题

在这里发挥了作用,我真的可以使用一些故障排除帮助。

代码从我的主/根App.vue移到Home.vue“视图”文件后,突然出现了一些反应性问题。

采用以下App.vue模板语法:

  <div id="app">
    <Header15 />
    <router-view />
    <UtilsBar />
    <Footer15 />
  </div>
</template>

在我的Home.vue文件中定义的有问题的模板语法代码段:

<ul class="filter-list">
  <li class="filter-list__litem" v-for="theme in themeFilterButtons" :key="theme.id">
    <a class="filter-list__link" :class="{ 'on': theme.isActive }" :href="'#'+theme.id" @click.prevent="onFilterSelect('theme',theme.id)">
      {{ theme.isActive }}<br />
      {{ theme.text }}
    </a>
  </li>

themeFilterButtons是对象的计算数组。

computed: {
  themeFilterButtons() {
    return this.filters.themes.map((theme) => {
      return { ...theme,isActive: false };
    });
  }
}

新数组引用了我的过滤器对象中的一个数组(主题);在我的数据中是这样定义的:

data() {
  return {
    filters: {
      themes: [
        { id: 113,text: 'First World War' },{ id: 214,text: 'Second World War' }
      ]
    }
  }
}

绑定到click事件的onFilterSelect方法最终调用了另一个方法filterBtnSelToggle。该方法通过切换对象上的.on属性来切换选定的类(isActive)。

为了进行故障排除,我简化了该函数,以尝试执行将第一个数组索引的isActive属性设置为true的特殊任务。由于最初将其设置为false,因此单击任何按钮都应将属性更改为true。无论我如何设置该模板视图(v-for)都不会更新。我尝试了所有这些,没有更新标记

onFilterSelect(cat,id) {
  // Say I wanted to set isActive: true on the first array item.
  this.themeFilterButtons[0].isActive = true; // < Doesn't work.
  this.$set(this.themeFilterButtons[0],'isActive',true); // < nope,also doesn't work.
  console.log('this.themeFilterButtons[0].isActive'); // Returns true.
}

登录到控制台的所有内容都会返回我期望的结果,只是模板(标记内容无法更新。

就像我说的那样,奇怪的是,如果我将逻辑移回到主App.vue文件中,它将继续有效...

非常感谢您的帮助!

解决方法

在这种情况下,计算属性取决于this.filters.themes,并且您始终将isActiv设置为false。因此您可以将themeFilterButtons设置为数据属性 它可以工作

  // delete computed Code block set themeFilterButtons property in data 
  mounted() {
    this.themeFilterButtons = this.filters.themes.map((theme) => {
      return { ...theme,isActive: false };
    });
  },
,

您可以尝试使用getter setter计算属性。

computed: {
  themeFilterButtons: {
    get () {
      return this.filters.themes.map((theme) => {
        return { ...theme,isActive: false };
      });
    }
    set (val) {
      this.filters = val
    }
  }
}

但是,更好的方法是先在isActive中定义data

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。