实现:一个商品列表,每个商品包含商品名称、商品价格,我们可以对每个商品进行删除操作,要求如下。
效果如下图所示
?
?
?接下来是代码,看代码标题就知道放在哪里了
<!-- GoodsList.vue -->
<template>
<ul>
<li v-for="(good, index) in goods" :key="index">
<span>{{ good.name }}</span>
<span>{{ good.price.toFixed(2) }}</span>
<button @click="deleteGood(index)">删除</button>
</li>
</ul>
</template>
<script>
export default {
props: {
goods: {
type: Array,
required: true,
},
},
methods: {
deleteGood(index) {
this.$emit('delete', index);
},
},
};
</script>
<style scoped>
ul {
padding: 0;
}
li {
list-style: none;
width: 400px;
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
button {
padding: 5px 10px;
background-color: #ddd;
border: none;
cursor: pointer;
}
</style>
<!-- NoData.vue -->
<template>
<p>没有数据</p>
</template>
<style scoped>
p {
color: red;
}
</style>
<!-- App.vue -->
<template>
<div id="app">
<button @click="reset">还原</button>
<goods-list :goods="goodsList" @delete="delGood" />
<no-data v-if="goodsList.length === 0" />
</div>
</template>
<script>
import GoodsList from './components/GoodsList.vue';
import NoData from './components/NoData.vue';
export default {
components: {
GoodsList,
NoData,
},
data() {
return {
goodsList: [
{ name: '电饭煲', price: 200.133232 },
{ name: '电视机', price: 880.998392 },
{ name: '电冰箱', price: 650.2034 },
{ name: '电脑', price: 4032.9930 },
{ name: '电磁炉', price: 210.4322 },
],
};
},
methods: {
delGood(index) {
this.goodsList.splice(index, 1);
},
reset() {
this.goodsList = [
{ name: '电饭煲', price: 200.133232 },
{ name: '电视机', price: 880.998392 },
{ name: '电冰箱', price: 650.2034 },
{ name: '电脑', price: 4032.9930 },
{ name: '电磁炉', price: 210.4322 },
];
},
},
};
</script>
<style scoped>
#app ul li {
list-style: none;
width: 400px;
display: flex;
justify-content: space-between;
}
</style>
// main.js
import Vue from 'vue';
import App from './App.vue';
new Vue({
render: (h) => h(App),
}).$mount('#app');
快尝试一下吧。记得点赞!