1.请求商品列表的数据
const goodslist = ref([]);
const getGoodsList = async () => {
const res = await axios.get("https://www.escook.cn/api/goods");
if (res.status !== 200) return console.log("获取商品列表数据失败!");
goodslist.value = res.data.data;
};
watchEffect(() => {
getGoodsList();
});
2.封装MyTable组件
<script setup>
defineProps({
data: Array,
default: [],
});
</script>
<template>
<div class="home container">
<table class="table table-bordered table-striped">
<!-- 标题区域 -->
<thead>
<tr>
<!-- 具名插槽 -->
<slot name="header"></slot>
</tr>
</thead>
<!-- 内容主体区域 -->
<tbody>
<!-- 作用域插槽 -->
<tr v-for="item in data" :key="item.id">
<slot name="body" :row="item"></slot>
</tr>
</tbody>
</table>
</div>
</template>
<template>
<MyTable :data="goodslist">
<template #header>
<th>序号</th>
<th>商品名称</th>
<th>价格</th>
<th>标签</th>
<th>操作</th>
</template>
<template #body="{ row }">
<td>{{ row.id }}</td>
<td>{{ row.goods_name }}</td>
<td>¥{{ row.goods_price }}</td>
<td>{{row.tags}}</td>
<td>
<button
type="button"
class="btn btn-danger btn-sm">
删除
</button>
</td>
</template>
</MyTable>
</template>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a1bb241e5211a03d5e8771faf27ac84f.png)
3.实现删除功能
<template>
<MyTable :data="goodslist">
<template #header>
<th>序号</th>
<th>商品名称</th>
<th>价格</th>
<th>标签</th>
<th>操作</th>
</template>
<template #body="{ row }">
<td>{{ row.id }}</td>
<td>{{ row.goods_name }}</td>
<td>¥{{ row.goods_price }}</td>
<td>{{ row.tags }}</td>
<td>
<button
type="button"
class="btn btn-danger btn-sm"
@click="onRemove(row.id)"
>
删除
</button>
</td>
</template>
</MyTable>
</template>
const onRemove = (id) => {
goodslist.value = goodslist.value.filter((x) => x.id !== id);
};
4.循环渲染tag标签
<td>
<!-- 循环渲染标签信息 -->
<el-tag
type="warning"
class="mx-1"
effect="dark"
v-for="item in row.tags"
:key="item"
>
{{ item }}
</el-tag>
</td>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/660d24c7ed8cf2642849a76dc1992ef7.png)
5.在标签中实现input和button
const onInputConfirm = (row) => {
const val = row.inputValue;
row.inputValue = "";
row.inputVisible = false;
if (!val || row.tags.indexOf(val) !== -1) return;
row.tags.push(val);
};
<el-input v-model.trim="row.inputValue" placeholder="Please input" v-if="row.inputVisible" @blur="onInputConfirm(row)" @keyup.enter="onInputConfirm(row)" @keyup.esc="row.inputValue=''"/>
<el-button type="success" size="small" v-else @click="row.inputVisible=true">+tag</el-button>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0d2e144ee4feb28963c9e19903d9c961.png)