为什么要数据持久化
页面一刷新,刚刚操作的数据就没了main.js
Vue.prototype.$bus=new Vue();
App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<h1>{{ title }}</h1>
<ul>
<li v-for="(item, index) in cartList" :key="item.id">
<h2>{{ item.title }},价格:{{ item.price }}</h2>
<button @click='addCart(index)'>添加购物车</button>
</li>
</ul>
<MyCart :title="title"></MyCart>
<!-- 3.使用 -->
</div>
</template>
<script>
import MyCart from "./components/Cart.vue"; // <!-- 1.导入 -->
export default {
name: "App",
data() {
return {
cartList: [
// { id: 1, title: "Vue实战开发", price: 66, count:2 },
// { id: 2, title: "Django实战开发", price: 88, count:3 },
],
};
},
methods: {
addCart(i){
const good = this.cartList[i];
this.$bus.$emit('addCart', good);
}
},
async created() {
try {
const res = await this.$http.get("/api/cartList");
this.cartList = res.data.result;
} catch (error) {
console.log(error);
}
},
components: {
MyCart, // <!-- 2.挂载 -->
},
};
</script>
<style>
#app {
}
</style>
Cart.vue
<template>
<div>
<h2>{{ title }}</h2>
<table border="1">
<tr>
<th>#</th>
<th>课程</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
</tr>
<tr v-for="c in cart" :key="c.id">
<td>
<input type="checkbox" v-model="c.active" />
</td>
<td>{{ c.title }}</td>
<td>{{ c.price }}</td>
<td>
<button>-</button>
{{ c.count }}
<button>+</button>
</td>
<td>{{ c.price * c.count }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "cart",
props: ["title"],
data() {
return {
cart: [],
};
},
created() {
// $on 绑定事件
this.$bus.$on("addCart", (good) => {
const ret = this.cart.find((v) => v.id === good.id);
console.log(ret);
if (!ret) {
//购物车没有数据
this.cart.push(good);
}else{
ret.count += 1;
}
});
},
};
</script>
<style lang="sass" scoped>
</style>
如何做数据持久化
Cart.vue
<template>
<div>
<h2>{{ title }}</h2>
<table border="1">
<tr>
<th>#</th>
<th>课程</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
</tr>
<tr v-for="c in cart" :key="c.id">
<td>
<input type="checkbox" v-model="c.active" />
</td>
<td>{{ c.title }}</td>
<td>{{ c.price }}</td>
<td>
<button>-</button>
{{ c.count }}
<button>+</button>
</td>
<td>{{ c.price * c.count }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "cart",
props: ["title"],
data() {
return {
cart: JSON.parse(localStorage.getItem('cart')) || [],
};
},
watch:{
cart: {
handler(n){
this.setLocalData(n);
},
deep: true
}
},
methods:{
setLocalData(n){
localStorage.setItem('cart', JSON.stringify(n))
}
},
created() {
// $on 绑定事件
this.$bus.$on("addCart", (good) => {
const ret = this.cart.find((v) => v.id === good.id);
console.log(ret);
if (!ret) {
//购物车没有数据
this.cart.push(good);
}else{
ret.count += 1;
}
});
},
};
</script>
<style lang="sass" scoped>
</style>
$bus显得有点臃肿,用vuex会更方便。