vue.js - 如何在 VueJS 中有一个作用域切换变量
问题描述
我来自 AngularJS 背景,其中 ng-repeat 有一个作用域变量,我试图弄清楚如何在不需要创建一个新组件的情况下实现类似的结果,这在很多情况下似乎有点矫枉过正。
例如:
<div class="item" v-for="item in items">
<div class="title">{{item.title}}</div>
<a @click="showMore = !showMore">Show more</a>
<div class="more" v-if="showMore">
More stuff here
</div>
</div>
在 AngularJS 中,该代码会很好用,但是在 VueJS 中,如果您单击显示更多,它会导致变量为项目列表中的每个项目更新,无论如何要在 v-for 内创建一个局部范围变量without the need to make a new component?
showMore
我可以通过将变量设置为@click="showMore = item.id"
then来使其工作,v-if="showMore.id = item.id"
但是对于应该更简单的东西来说,这似乎也太复杂了?该方法的另一个问题是您只能让一个项目显示更多,而不是允许一次切换显示多个项目。
我还尝试将items
模型更改为包含item.showMore
,但这又增加了更多复杂性,如果由于模型更改而需要更新单个项目,则会导致问题。
有没有更简单的方法呢?
解决方案
您对此有何看法:CODEPEN
<template>
<div>
<h1>Items</h1>
<div v-for="item in items"
:key="item.id"
class="item"
>
{{item.name}}
<button @click="show=item.id">
Show More
</button>
<div v-if="item.id == show">
{{item.desc}}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{id:1, name:"One", desc: "Details of One"},
{id:2, name:"Two", desc: "Details of Two"},
{id:3, name:"Three", desc: "Details of Three"}
],
show: null
};
}
};
</script>
<style>
.item{
padding: 5px;
}
</style>
推荐阅读
- mongodb - Mongodb查询返回字段值
- sql-server - 在 SQL 代理作业中由 SSIS 项目 FTP 任务下载时损坏的图像
- android - 我可以使用除我开发的 Android 应用程序以外的任何浏览器限制访问我的网站吗?
- openstreetmap - 如何在一个行政区域内找到所有方法
- python - 使用带有构造函数的 MySQL 连接器
- c - 为什么在 MASM 汇编中使用 FPU x87 指令集执行操作时得到无意义的数字?
- javascript - 不调用 ES6 导入
- wordpress - WordPress 自定义查询字符串未被 Google 索引
- css - HighCharts 组织节点重叠
- javascript - HttpRequest 和 XMLHttpRequest 之间的真正区别