思路整理
主要涉及知识点:
- vue 如何创建并运行项目 vue create xxx;
- 如何定义data() { return {} }及渲染数据 {{stu}};
- 如何定义移除/增添函数; 添加form表单; 提交数据;
- filter() 方法的使用来遍历并过滤数组;
- 如何阻止函数的默认行为: e.preventDefault() ;
- 如何拷贝对象 const stu = Object.asign({}, this.stu) ;
- push() 方法的使用, 为数组添加元素
- 清空表单
代码块
<template>
<div id="app">
<form action="">
<input type="text" v-model="stu.id">
<input type="text" v-model="stu.name">
<input type="text" v-model="stu.age">
<input type="submit" value="确定" @click="addStu">
</form>
<ul>
<li v-for="(stu, index) in stus" :key = "stu.id" @click="remStu(index)">
{{stu.id}} ---- {{stu.name}} ---- {{stu.age}}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
stus: [
{id: 1, name: 'sonia', age: 12},
{id: 2, name: 'bolin', age: 22},
{id: 3, name: 'alice', age: 32}
],
stu: {
id: '',
name: '',
age: ''
}
}
},
methods: {
// 移除
remStu(index) {
// 如果点击的 idx 与 当前 list 的 index 一样,则筛选掉, 否则保留
// filter()过滤后组成的数组 赋值给 stus
this.stus = this.stus.filter((stu, idx)=>idx !== index)
},
// 增加
addStu(e) {
// 阻止默认行为
e.preventDefault()
// 拷贝对象
const stu = Object.assign({}, this.stu)
// 推送到 stus 数组里
this.stus.push(stu)
this.stu.id = '',
this.stu.name = '',
this.stu.age = ''
}
}
}
</script>
<style>
</style>
后记
按思路走下来,感觉很顺,掌握 vue2 就能很轻松的写出一个 TODO-list 样式按自己喜好,重点是掌握知识点用法!