gpt4 book ai didi

javascript - 使用索引时,Vue 不会触发模板中 v-if 内部的更改

转载 作者:行者123 更新时间:2023-12-01 22:48:37 25 4
gpt4 key购买 nike

我有一些项目,每个项目都有一个描述,末尾有一个显示更多链接。单击此链接,我想触发一个功能。
但是,该方法会正确触发并在控制台中打印结果,但不会在 Vue 模板中触发更新。

完整代码如下:

   <template>
<main>
<div class="card" v-for="(item, index) in items" :key="index">

<div class="content">
<h3 class="card-title">{{item.name}} </h3>
<p v-if="showMoreText[index]">{{ item.description }}</p>
<p v-else>{{ item.description.substring(0, 100) }}...<span class="link" @click="showMore(index)">show more</span></p>
</div>
</div>
</main>
</template>

<script>
export default {
data() {
return {
showMoreText: []
}
},
props: {
items: Array,
},
created() {
for (let i = 0; i < this.items.length; i++) {
this.showMoreText[i] = false;
}
},
methods: {
showMore(index) {
this.showMoreText[index] = !this.showMoreText[index]
// console.log(this.showMoreText[index])
}
},
}
</script>

最佳答案

您遇到这个问题是因为您的数据不是 react 性的。

根据documentation -

Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

您面临的问题是第一种情况,要解决它,您需要使用 Vue.set 方法使数据具有反应性-

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// You can also use the vm.$set instance method, which is an alias to the global Vue.set:
this.$set(vm.items, indexOfItem, newValue)

这是您的问题的工作演示-

.link {
color: blue;
cursor: pointer;
}
<html>
<div id="app">
<div class="card" v-for="(item, index) in items" :key="index">
<div class="content">
<h3 class="card-title">{{ item.name }}</h3>
<p v-if="showMoreText[index]">{{ item.description }}</p>
<p v-else>
{{ item.description.substring(0, 10) }}...<span
@click="showMore(index)"
><span class="link">show more</span></span
>
</p>
</div>
</div>
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
new Vue({
el: "#app", //Tells Vue to render in HTML element with id "app"
data() {
return {
showMoreText: [],
items: [
{
name: "name1",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
},
{
name: "name2",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
},
{
name: "name3",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
},
{
name: "name4",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
},
],
};
},
mounted() {
for (let i = 0; i < this.items.length; i++) {
this.showMoreText[i] = false;
}
},

methods: {
showMore(index) {
this.$set(this.showMoreText, index, !this.showMoreText[index]);
},
},
});
</script>
</html>

关于javascript - 使用索引时,Vue 不会触发模板中 v-if 内部的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74854103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com