阵列更改不会重新呈现模板

时间:2020-09-15 21:12:14

标签: vuejs2 vue-composition-api

我有一个组件,只有在更改唯一值时,模板才会更新:

setup(prop) {
  const uniqueValue = ref(1);
  const fullStar = ref(['fillerValue', false, false, false, false, false]);

  const displayRating = (rating: number) => {
    uniqueValue.value += 1;
    for (let index = 1; index <= rating; index++) {
      fullStar.value[index] = true;
    }
  };

  return {
    uniqueValue,
    fullStar,
  }

<template>
  <div class='ratingContainer'
    v-on:mouseleave='displayRating(storedRating)'>
    <div v-for='n in 5' :key='n'>
      <StarIcon v-if='fullStar[n]' />
      <div style="display: none">{{ uniqueValue }}</div>
    </div>
  </div>
</template>

我有一个名为fullStar的数组,我想根据传递给displayRating函数的等级在模板中显示一些星星。

但是,即使uniqueValue数组值也发生了变化,模板也仅在我在模板中使用fullStar值时才重新呈现。

1 个答案:

答案 0 :(得分:0)

Looks like Vue is having some trouble with reactivity and array values。就像有人在那个问题上说的那样:

只需在对象中加入一个数组即可。这很好。与之前vue 2中的数据对象类似:

setup() {  
const fullStar = reactive({
  list: [
    { value: false },
    { value: false },
    { value: false },
    { value: false },
    { value: false },
    { value: false },
  ],
});

displayRating = (rating: number) => {
  for (let index = 1; index <= rating; index++) {
     // when this function is called it will set a number of objects in the list array to true and it will update the template.
     fullStar.list[index].value = true
  }
}

return { fullStar };
}

<template>
  <div class='ratingContainer'
    v-on:mouseleave='displayRating(storedRating)'>
    <div v-for='n in 5' :key='n'>
      <StarIcon
        v-if='fullStar.list[n].value' />
    </div>
  </div>
</template>