Two ways to get the value by pressing the Enter key in a Vue component
Install npm install nanoid
, import and call nanoid()
the function in the code to generate a random id value
The first: use
event
to get data
<template>
<div>
<input type="text" placeholder="请输入你的信息,按回车键确认" v-model="title" @keyup.enter="add"/>
<div/>
</template>
<script>
import {
nanoid} from 'nanoid'
export default {
name:'AddMessage',
methods: {
add(event){
// 将用户的输入包装成一个todo对象
const todoObj = {
id:nanoid(),title:event.target.value,done:false)
}
}
}
</script>
The second: use
v-model
two-way binding data
<template>
<div>
<input type="text" placeholder="请输入你的信息,按回车键确认" v-model="title" @keyup.enter="add"/>
<div/>
</template>
<script>
export default {
name:'AddMessage',
data(){
return {
title:''
}
},
methods: {
add(){
// 校验数据
if(!this.title.trim()) return alert('输入不能为空')
// 将用户的输入包装成一个对象
const todoObj = {
id:nanoid(),title:this.title,done:false),
// 将输入框的数据进行清除
this.tite = ''
}
}
}
</script>