我有一些项目,每个项目都有一个说明,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>
Run Code Online (Sandbox Code Playgroud)
您面临这个问题是因为您的数据不是反应性的。
根据文件-
Vue 无法检测到数组的以下更改:
- 当你直接用索引设置一个项目时,例如
vm.items[indexOfItem] = newValue- 当你修改数组的长度时,例如
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)
Run Code Online (Sandbox Code Playgroud)
这是您的问题的工作演示 -
// 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)
Run Code Online (Sandbox Code Playgroud)
.link {
color: blue;
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)