需求:在点击一个按钮的时候,一个按钮对应着一个弹窗。
代码:
<template>
<div class="">
<table>
<thead>
<tr>
<th>产品名称</th>
<th>数量</th>
<th>价格</th>
<th>库存</th>
</tr>
</thead>
<tbody>
<!-- 第一行 -->
<tr @click="fn(index)" v-for="(item, index) in arr" :key="index">
<td>{
{ item.name }}</td>
<td>{
{ item.allnum }}</td>
<td>{
{ item.price }}</td>
<td>{
{ item.shenyu }}</td>
</tr>
<!-- 第二行 -->
<tr v-for="(item, index) in arr" :key="index">
<td v-if="index == pageindex" colspan="4">
<One :code="item.code"> </One>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
// 导入组件
import One from "@/components/One.vue";
export default {
components: {
One,
},
data() {
return {
pageindex: null,
arr: [
{
name: "小米",
code: 1,
allnum: 500,
price: 1999,
shenyu: 300,
},
{
name: "oppo",
code: 2,
allnum: 300,
price: 1999,
shenyu: 200,
},
{
name: "华为",
code: 3,
allnum: 200,
price: 1999,
shenyu: 100,
},
{
name: "vivo",
code: 4,
allnum: 700,
price: 1999,
shenyu: 300,
},
],
};
},
name: "",
methods: {
fn(index) {
if (this.pageindex == index) {
// 如果变量的值等于索引的值将变量的值变成null
this.pageindex = null;
} else {
// 否则将索引的值赋值给变量
this.pageindex = index;
}
},
},
};
</script>
<style scoped>
table {
width: 300px;
margin: 100px auto;
border: 1px solid #ccc;
/* 合并单元格的线条 */
border-collapse: collapse;
}
th {
border: 1px solid pink;
}
td {
border: 1px solid blue;
}
</style>
子组件:
<template>
<div class="">
<h1>{
{ code }}</h1>
</div>
</template>
<script>
export default {
props: {
code: {
default: "String",
require: true,
},
},
name: "",
methods: {},
};
</script>
<style scoped></style>
view:
思路分析:
在进行第一次点击的时候, 会进入自己写的判断里面。
变量的值为:null 索引的值为:0
此时不相等,就会对变量就行赋值:
this.pageindex = index;
通过v-if="index == pageindex" 变量和索引进行判断
两者的值是一样的,此时就应该显示当前行的弹窗。
在进行第二次点击的时候。
变量的值为:0, 索引的值:0。
this.pageindex = null;
将变量的值赋值为null。
此时
v-if="index == pageindex"
v-if="false",弹窗显示将会进行关闭。
赋值变量的值是否可以任意设置?
梳理一下思路:
首次点击:v-if='true'
再次点击:v-if='false'
通过判断变量的值和索引的值是否相等来决定是否显示和隐藏。
第一次点击过去,打开弹窗,变量和索引的值肯定是相等的。
索引的值是固定的,一行对应着一个索引。
变量的值可以等于其他的值,当最好别和索引相互冲突。
在此点击的时候,因为变量的值和索引的值相等了索引这个时候让它不相等。
一直循环下去的一个状态。
相等-----------------true
不相等----------------false
相等----------------------true
不相等-----------------false
这样就实现了切换。
用一个图表进行表示: