使用Composition API清空input输入框的问题

来源:2-7 使用 Composition API 开发TodoList(1)

weixin_慕勒4195760

2021-01-07 13:00:27

关键代码如下:

<script>
const app = Vue.createApp({

setup() {
// 定义数据
const {ref, reactive} = Vue;
const inputValue = ref('');
const list = reactive([]);

// 输入框改变事件
const handleChange = (e) => {
inputValue.value = e.target.value;
}

// 提交按钮事件
const handleSubmit = () => {
list.push(inputValue);
}

return {
inputValue,
list,
handleChange,
handleSubmit
}
},

template: `
<div>
<div>
<input :value="inputValue" @input="handleChange" type="text">
<button @click="handleSubmit">提交</button>
</div>
<ul>
<li v-for="(item, index) of list" :key="index">{{ item.value }}</li>
</ul>
</div>
`

});

app.mount("#root");
</script>​

老师,我想要实现输入以后清空input输入框,我试了几次都没有实现,老湿看下如何修改呢?




写回答

1回答

好帮手慕久久

2021-01-07

同学你好,这样写不正确。点击提交按钮后,再次修改input中的值,下拉列表的内容,也会同步改变:

http://img.mukewang.com/climg/5ff6bfc9098b1b7003960124.jpg

原因是list中追加的值是inputValue(它是响应式的)。当input框中输入内容时,会触发input事件,该事件处理函数中会修改inputValue的值,由于inputValue是响应式的,所以list中的inputValue会同步变,因此下拉列表的内容会跟随输入内容而变化。此时无法实现将输入框内容置为空(该步操作需要修改inputValue的值为空,会影响下拉列表中显示的内容)。

建议将inputValue作为参数,传入到handleSubmit事件中,如下:

http://img.mukewang.com/climg/5ff6c19d09645d6811980294.jpg

http://img.mukewang.com/climg/5ff6c14c09d6aad509340195.jpg

此时,参数val只是 inputValue对象的value值,可以打印list看一下:

http://img.mukewang.com/climg/5ff6c20c094fcb8106650156.jpg

所以遍历list渲染内容时,需要做如下更改:

http://img.mukewang.com/climg/5ff6c25009443f6708480166.jpg

这样就可以实现清空输入框了:

http://img.mukewang.com/climg/5ff6c17709f6ed2d05170159.jpg

祝学习愉快!

0

0 学习 · 15276 问题

查看课程