项目场景:
用vue.js 3.0实现简易记事本功能,需求如下:
- 用户在文本框中输入需要记录的内容,然后按enter键把输入的内容加入到记事本中
- 单击某一条记录后面的“删除”按钮可以删除对应的记录
- 在记事本最下方可显示一共有多少记事条数
- 在记事本内容的最下方单击“清除所有记录”按钮,可以清除所有记事内容,并且隐藏最下方的条数和“清除所有记录”按钮。实现结果如下图所示
问题解决思路
- 先写出基本布局,再根据需求把功能拆解成一个一个小模块,实现基本功能之后再修饰样式
- 例如记事本功能可拆解为,添加输入框内容和删除对应条数等
源码实现:
<template>
<div>
<h2>简易记事本</h2>
<header id="top">
<input type="text" v-model="data.mrvalue" @keyup.enter="add" placeholder="请输入内容·" />
<ul id="lb">
<!-- v-for循环列出列表 -->
<li v-for="(item, index) in data.list" :key="index">
<!-- 前面的序号 -->
<span id="xh">{{ index + 1 }}</span>
<!-- 列表内容 -->
<span>{{ item }}</span>
<!-- 关闭按钮 -->
<!-- 添加点击移除事件,要传形参 -->
<button id="qc" @click="remove(index)">删除</button>
</li>
<!-- v-指令 当0时显示 -->
<span v-if="data.list.length> 0">
条数:{{ data.list.length }}
</span>
<!-- v-show指令 当>0时显示 -->
<button @click="clear" v-show="data.list.length > 0" id="clear">清除所有记录</button>
</ul>
</header>
</div>
</template>
<script>
import { reactive, toRefs } from 'vue'
export default {
setup() {
const state = reactive({
data: {
list: ['床前明月光', '疑是地上霜', '举头望明月'],
mrvalue: ""
}
})
const add = () => {
state.data.list.push(state.data.mrvalue),
state.data.mrvalue = ""
}
const remove = (index) => state.data.list.splice(index, 1);
const clear = () => state.data.list = []
return {
...toRefs(state),
add,
remove,
clear
}
}
}
</script>
<style scoped>
h2,
header {
margin-left: 150px;
}
input {
margin-left: 180px;
}
#lb {
list-style: none;
}
#lb li {
position: relative;
border-bottom: 1px solid black;
width: 400px;
height: 50px;
line-height: 50px;
}
#xh {
background-color: rgb(20, 49, 193);
padding: 10px;
margin-right: 10px;
height: 30px;
width: 30px;
border-radius: 10px;
}
#qc {
position: absolute;
top: 10px;
right: 0px;
color: white;
font-weight: bold;
background-color: rgb(233, 11, 41);
padding: 2px;
height: 30px;
line-height: 30px;
cursor: pointer;
}
#clear {
margin: 10px 100px;
}
</style>
项目总结:
对指令有了清楚的认识,掌握了v-if 和1v-model等指令,对于文本插值和事件处理表单输入绑定基础知识,有了进一步认识。