Vue实现todoList
Pcjmy2022-03-27VueVue
Vue 实现 todoList
实现思路
- 首先定义一个列表,这个列表需要具备响应式,考虑使用 reactvie
- 显示列表中的元素需要使用循环 v-for,列表下标作为 key 值
- 需要一个 input 框接收输入,这里采用 v-model 双向绑定
- 输入框的值需要时响应式的,这里使用 ref
- 提交 input 框的内容需要绑定事件,这里使用 v-on
<template>
<div>
<input v-model="inputValue" />
<button @click="handleAddItem">提交</button>
</div>
<ul>
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
</template>
<script>
import { reactive, ref } from "vue";
export default {
name: "App",
setup() {
const list = reactive([1, 2, 3]);
const inputValue = ref();
const handleAddItem = () => {
list.push(inputValue.value);
inputValue.value = "";
};
return { list, inputValue, handleAddItem };
},
};
</script>
<style></style>
注意
list 也可以定义为 ref,在 handleAddItem 中需要改为 list.value.push(),其他不变