Vue3 todolist 示例
Vue3 todolist 示例 新手入门示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue3 todolist 示例</title>
<style>
span {
display: inline-block;
padding: 0 8px;
}
</style>
</head>
<body>
<div id="app">
<div class="list">
<div v-for="(item, i) in list" :key="item.id" class="item">
<input type="checkbox" :checked="item.checked" @click="itemSelect(i, item)">
<span>{{item.name}}</span>
<span>¥{{item.price}}</span>
<span @click="itemEdit(i, item)">编辑</span>
<span @click="itemRemove(i, item)">删除</span>
</div>
</div>
<hr/>
<div>
<label><input type="checkbox" :checked="listAllSelected" @click="allSelectClick">全选</label>
<span>总价 {{totalPrice}}</span>
</div>
<hr/>
<div>
名称 <input type="text" v-model="current.name">
价格 <input type="number" v-model.number="current.price">
<input v-show="!current.id" @click="itemAdd" type="button" value="添加">
<input v-show="current.id" @click="itemEditSubmit" type="button" value="编辑">
<input @click="itemCancel" type="button" value="取消">
</div>
</div>
<script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/vue/3.1.2/vue.global.js"></script>
<script type="text/javascript">
function getList() {
// ajax 获取数据
return [
{ id: 1, name: 'Vue 入门指南', price: 65 },
{ id: 2, name: 'Less 入门指南', price: 35 },
{ id: 3, name: 'Scss 入门指南', price: 40 },
{ id: 4, name: 'H5 入门指南', price: 55 },
];
}
let id = 10;
const App = {
data() {
return {
list: [],
current: {
id: 0,
name: '',
price: 0,
},
};
},
computed: {
listAllSelected() {
return this.list.length === this.list.filter(v => v.checked).length;
},
totalPrice() {
return this.list.filter(v => v.checked).reduce((a, c) => a + c.price, 0);
},
},
mounted() {
this.list = getList().map(v => {
v.checked = false;
return v;
});
},
methods: {
itemAdd() {
if (this.current.name.trim() === '') { return alert('请输入名称'); }
if (this.current.price <= 0) { return alert('请输入价格'); }
const goods = {
id: 0,
name: this.current.name,
price: this.current.price,
}
// 调用 ajax 接口添加
goods.id = id++;
this.list.push(goods);
this.itemCancel();
},
itemEdit(i, item) {
this.current = {
id: item.id,
name: item.name,
price: item.price,
};
},
itemEditSubmit() {
if (this.current.name.trim() === '') { return alert('请输入名称'); }
if (this.current.price <= 0) { return alert('请输入正确的价格'); }
const index = this.list.findIndex(v => v.id === this.current.id);
if (index === -1) {
return;
}
this.list[index].name = this.current.name;
this.list[index].price = this.current.price;
this.itemCancel();
},
itemCancel() {
this.current = {
id: 0,
name: '',
price: 0,
};
},
itemSelect(i, item) {
item.checked = !item.checked;
},
itemRemove(i, item) {
this.list.splice(i, 1);
},
allSelectClick() {
const checked = this.listAllSelected;
this.list.forEach(v => v.checked = !checked);
},
},
};
Vue.createApp(App).mount('#app');
</script>
</body>
</html>