当使用index时,我们不会在模板中触发v-if内部的更改



我有一些项目,每个项目都有一个描述,最后有一个show more链接。在这个链接的点击,我想触发一个函数。
但是,该方法正确地触发并在控制台中打印结果,但是更新没有在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>

你正面临这个问题,因为你的数据不是反应性的。

根据文档-

Vue无法检测到数组的以下更改:

  1. 直接设置索引项时,如vm.items[indexOfItem] = newValue
  2. 修改阵列长度时,如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>

最新更新