在main.js引入elementUI,在vue.config.js造假数据 configureWebpack: {before:{app.get("/api/goods", function(req, res) {}} },造好的数据使用axios请求axios.get("./api/goods")
main.js:
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App.vue";
Vue.use(ElementUI);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
app.vue:
///* 使用elementui 和axios(在vue.congfig.js里面configureWebpack devServe before(app) 里面写app.get("url",data)放的数据)*/
<template>
<div>
<el-row>
<el-col :span="6" v-for="(item, index) in goods" :key="index">
<el-card>
<img :src="item.img" class="image" alt="books" />
<div style="padding:14px;">
<span>{{ item.title }}</span>
<el-button type="text" class="button">
<i class="el-icon-plus"></i>
添加
</el-button>
</div>
</el-card>
</el-col>
</el-row>
<h1>hello {{ title }}</h1>
<ul>
<li v-for="(good, index) in goods" :key="good.text">
{{ good.title }}
|
{{ good.price }}
<el-button @click="addCart(index)">添加购物车</el-button>
</li>
</ul>
<Cart :data="cart" @addF="onAdd" @reduceF="onReduce"></Cart>
</div>
</template>
<script>
import Cart from "./components/Cart";
import axios from "axios";
export default {
components: {
Cart
},
data() {
return {
title: "china",
goods: [
// { title: "高薪架构师", price: 100 },
// { title: "高薪全栈", price: 90 },
// { title: "高薪架高级", price: 30 }
],
cart: []
};
},
async created() {
let res = await axios.get("./api/goods");
this.goods = res.data.data;
console.log(res);
},
methods: {
addCart(i) {
console.log("添加购物车");
let item = this.goods[i];//商品
let good = this.cart.find(v => v.title == item.title);//判断商品是否在购物车里
if (good) {
good.count += 1;//在购物车,商品数量+1
} else {
this.cart.push({ ...item, count: 1 });//不在购物车即添加到购物车
}
},
onAdd(arg) {
let { index } = arg;
this.cart[index].count += 1;
},
onReduce(arg) {
let { index } = arg;
if (this.cart[index].count > 1) {
this.cart[index].count -= 1;
}
}
}
};
</script>
<style scoped>
h1 {
color: red;
}
.image {
width: 100%;
}
</style>
vue.config.js:
module.exports = {
chainWebpack: config => {
config.module
.rule("eslint")
.use("eslint-loader")
.loader("eslint-loader")
.tap(options => {
options.fix = true;
return options;
});
},
configureWebpack: {
//扩展webpack
devServer: {
before(app) {//造假数据,在.vue文件中利axios请求
app.get("/api/goods", function(req, res) {
res.json({
code: 0,
data: [{
id: 1,
title: "vue2.x精通11",
price: "100",
img: "/img/03.jpg",
count: 100
},
{
id: 2,
title: "vue2.x精通22",
price: "100",
img: "/img/03.jpg",
count: 100
},
{
id: 3,
title: "vue2.x精通33",
price: "100",
img: "/img/03.jpg",
count: 100
},
{
id: 4,
title: "vue2.x精通44",
price: "100",
img: "/img/03.jpg",
count: 100
},
{
id: 5,
title: "vue2.x精通55",
price: "100",
img: "/img/03.jpg",
count: 100
}
]
});
});
}
}
}
};