vue中的删除表格信息,居于组件交互,删除过程在父组件与子组件代码中分为六个步骤 按步骤更好理解
效果图
默认状态↓
删除状态↓
删除后↓
代码↓
父组件(页面)
<template>
<div class="box">
<table class="tab" style="border-collapse:collapse;width:80%;margin:10px auto;">
<tr>
<th>序号</th>
<th>工号</th>
<th>姓名</th>
<th colspan="2">操作</th>
</tr>
<tr v-for="(item,index) in user" :key="item.id" class="trr">
<td>{{index+1}}</td>
<td>{{item.hao}}</td>
<td>{{item.name}}</td>
<!-- 第一步 ===》 :dex='item.studentid'(父组件传给子组件) 子组件props来接收 ( props: ['dex'],) -->
<!-- 第五步 ====》 @ddd='ddd' 绑定一个自定义事件-->
<td>
<v-S :dex="item.studentid" @ddd="ddd"></v-S>
</td>
</tr>
</table>
</div>
</template>
<script type='text/ecmascript-6'>
import vS from "../components/shan";
export default {
components: {
vS
},
props: [],
data() {
return {
user: [
{
studentid: 1,
hao: 1234567,
name: "尹善英"
},
{
studentid: 2,
hao: 11544567,
name: "三吉彩花"
},
{
studentid: 3,
hao: 15541657,
name: "尹素婉"
},
{
studentid: 4,
hao: 16645567,
name: "没有小熊了"
},
{
studentid: 5,
hao: 123455467,
name: "斋藤飞鸟"
}
]
};
},
watch: {},
computed: {},
methods: {
//第六步 ====》 e是子组件返回来的ID (item.studentid)
ddd(e) {
//遍历this.user 看this.user的studentid 与子组件返回来的ID(e) 谁是相同的
var index = this.user.findIndex(item => item.studentid == e);
//删除这条ID信息
this.user.splice(index, 1);
}
},
created() {},
mounted() {}
};
</script>
<style scoped>
.box {
width: 100vw;
height: 100vh;
margin: 20px auto;
background: #cccccc;
overflow: hidden;
}
.tab {
border: 3px solid #333333;
overflow: hidden;
}
tr,
td {
border: 3px solid #333333;
overflow: hidden;
}
.trr {
text-align: center;
overflow: hidden;
}
</style>
子组件 (删除按钮)
<template>
<div>
<button class="gong" @click="onoff=true" >删除</button>
<div class="msin" v-if="onoff" @click.self="onoff=false">
<div class="box">
<h1>你要删除吗?</h1>
<!-- 第三步====》 创建一个点击事件 (@click='del')-->
<button class="gong" @click='del'>删除</button>
<button @click="onoff=false">取消</button>
</div>
</div>
</div>
</template>
<script type='text/ecmascript-6'>
export default {
components: {},
// 第二步====》 props: ['dex'],接收父元素传过来的dex值(:dex='item.studentid')
props: ['dex'],
data () {
return {
onoff:false
};
},
watch: {},
computed: {},
methods: {
//第四步====》 this.$emit('ddd',this.dex) 告诉父组件是谁给我传的ID值,我要删除这个ID (告诉父组件)
// 'ddd' 是随意定的一个值 this.dex 父组件传过来的ID值 (item.studentid)
del(){
this.onoff=false
//子组件可以使用 $emit 触发父组件的自定义事件。
this.$emit('ddd',this.dex)
}
},
created () {},
mounted () {}
};
</script>
<style scoped>
.gong{
background: red;
color: #ffffff;
outline: none;
border-radius: 5px;
padding:5px 10px;
display: inline-block;
}
.msin{
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
position: fixed;
left: 0px;
top: 0px;
}
.box{
width: 300px;
height: 200px;
background: #ffffff;
position: absolute;
left:0px;
top: 0px;
right: 0px;
bottom: 0px;
margin: auto;
}
</style>