转自:https://www.jianshu.com/p/5421cebce523
设置基本的样式
- 要求:vue通过传入数据,进行页面渲染
- 利用指令来完成项目(如有疑惑可查看Vue官网文档)
- v-bind:key,简写为:key
- :class也是简写形式下面同理
- v-on:click简写为@click,给按钮绑定事件
<div id="app">
<h1>新增</h1>
<!-- v-model数据的双向绑定 -->
<input type="text" v-model="value">
<button @click="addAction">新增</button>
<h1>列表</h1>
<ul>
<!-- v-for循环生成显示列表里面的事件,赋予新的key,判断状态是否为finished 是则添加类名finished-->
<li v-for="(item,index) in showList"
:key="item.id"
:class="{finished:item.status==='finished'}">{{item.value}}
<!-- v-if判断上面li循环的item.id值,新添加的事件id为todo后面添加按钮,点击完成 -->
<button v-if="item.status ==='todo'"
@click="finiHandler(item.id,index)">完成</button>
</li>
</ul>
<h1>操作</h1>
<!-- v-for循环生成[所有,完成,未完成]按钮,选中的按钮添加类名active,添加点击事件改变item.id -->
<button v-for="(item,index) in btnList"
:key="item.id"
:class="{active:item.id===selected }"
@click='changeHandler(item.id)'>{{item.text}}</button>
</div>
设置css样式
- 通过类名改变对应的标签样式
<style>
.finished {
text-decoration: line-through;
}
.active {
background-color: yellow;
}
</style>
实现todolist的核心代码
//引入vue.js文件
<script src="vue.js"></script>
<script>
//实例化一个vm对象
var vm = new Vue({
// 作用域
el:"#app",
// 数据属性
data:{
// 初始数据
value:'',
// 选中'所有'这个按钮
selected:"all",
// 存放数据的数组
list:[],
// 按钮列标[所有,完成,未完成]
btnList:[
{text:"所有",id:"all"},
{text:"完成",id:"finished"},
{text:"未完成",id:"todo"}
]
},
computed:{
showList(){
// 显示selected选中的
return this.selected ==='all'? this.list:this.list.filter(item=>item.status===this.selected)
}
},
methods:{
//添加事件到list列表[1]
addAction(){
this.list.push({
value:this.value,
status:'todo',
// 用时间戳记录id数据唯一性
id:new Date().getTime(),
});
// 清空input框
this.value='';
},
// 点击完成按钮事件函数[w]
finiHandler(id,index){
// 找到list数组里面id等于点击的按钮的id
// 改变这个对象的status为finished
const item = this.list.find((item) =>item.id===id)
item.status ='finished'
},
// [所有,完成,未完成]按钮的切换事件函数[3]
changeHandler(id){
// 改变selected为当前选中按钮的id值
this.selected = id
},
}
});
</script>
</body>
[1]
- 输入框输入事情,点击新增按钮显示在列表里面
[2]
- 点击"完成"按钮之后,文字增加删除线
[3]
- 切换按钮查看 所有事件,完成事件,未完成事件
更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。