封装--localStorage本地化存储[持久化]
封装--localStorage本地化存储_tby_pr的博客-CSDN博客
<script src="./js/vue.js"></script>
<div id="app">
<table width='600' border="1">
<tr>
<th>ID</th>
<th>名称</th>
<th>数量</th>
<th>单价</th>
<th>合计</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in carts" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<button @click="item.num = Math.max(1,--item.num)">-</button>
<input type="text" v-model.number="item.num">
<button @click="addNum(item)">+</button>
</td>
<td>{{item.price}}</td>
<td>{{item.num*item.price}}</td>
<td>
<button>删除</button>
</td>
</tr>
</table>
<hr>
<div>总计:{{totalPrice()}}</div>
</div>
//导入 封装好的 本地存储
<script src="./js/Store.js"></script>
<script>
const store = new Store;
const key = 'carts'
// 下面的代码开一次就好了,存进storage
store.set(key, [
{ id: 1, name: '小米手机', price: 1, num: 2 },
{ id: 2, name: '华为手机', price: 1, num: 3 },
])
const vm = new Vue({
el: '#app',
data: {
// 数据源 获取
carts: store.get(key)
},
methods: {
totalPrice() {
/* let total = 0;
this.carts.forEach(item => total += item.price * item.num)
return total */
return this.carts.reduce((p, item) => p += item.price * item.num, 0)
},
addNum(item) {
item.num = Math.min(5, ++item.num)
//改变本地化的数据
store.set(key, this.carts)
}
}
})
</script>