繁体   English   中英

Vue.js 奇怪的反应性问题

[英]Vue.js strange reactivity issue

我在这里不知所措,我真的可以使用一些故障排除帮助。

在将代码从我的主/根App.vueHome.vue “视图”文件后,我突然App.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' }
      ]
    }
  }
}

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

为了排除故障,我简化了函数以尝试执行将第一个数组索引上的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
    }
  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM