Press the Enter key in the Vue component to get the value value

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 eventto 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-modeltwo-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>

Guess you like

Origin blog.csdn.net/qq_53810245/article/details/122953705