先来看一下效果:
下面是实现代码与思路:
src/App.vue中
<template>
<div>
<h2>我的购物车</h2>
<ul>
<li v-for="(item, index) in books" :key="index">
<img :src="item.img" alt="" />
<span>{{ item.name }}¥</span>
<p>{{ item.price }}¥</p>
<div class="off" @click="del(index)">×</div>
</li>
</ul>
</div>
</template>
<script>
// 目标
// 1. 完成数据的渲染 v-for
// 2. 点击x号 删除数据
// 步骤
// 下载axios
// 1. 在App组件页面引入axios
// 2. 实例化
// data: 创建空数组,
// methods: 定义要删除的第i项
// 3.在 created 发起axios 异步请求
// 渲染数据
// v-for
// 点击 - ,删除元素
// 思路 :
// 1. 给 x 添加点击事件
// 2. 在事件的回调中删除books中的数据项
import axios from "axios";
export default {
data() {
return {
books: [],
};
},
methods: {
del(index) {
// 如何去删除数组第i项?
// arr.splice(元素的起点,要删除几项)
this.books.splice(index, 1);
},
},
created() {
axios({
//发起axios异步请求
url: "https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books",
method: "get",
}).then((res) => {
console.log("请求的数据", res); //请求的数据
this.books = res.data.data;
});
},
};
</script>
<style lang="less" scoped>
h2 {
text-align: center;
}
li {
position: relative;
width: 190px;
height: 240px;
list-style: none;
float: left;
box-shadow: 3px;
}
p {
color: red;
}
img {
width: 180px;
height: 200px;
}
.off {
position: absolute;
right: 20px;
top: 5px;
width: 25px;
height: 25px;
background-color: #ccc;
text-align: center;
border-radius: 15px;
}
.off:hover {
background-color: rgb(238, 14, 14);
}
</style>