Vue uses computed to implement one-way binding and two-way binding of computed properties

As shown in the picture:

insert image description here
Purpose: When modifying the name, modify the full name, and modify the name information when modifying the full name

1. Add four inputs to the page, save the last name, first name, full name 1, and full name 2 respectively

<div id="app">
      姓: <input placeholder="First Name" v-model="firstName" /><br />
      名: <input placeholder="Last Name" v-model="lastName" /><br />
      姓名1(单向): <input placeholder="Full Name1" v-model="fullName1" /><br />
      姓名2(双向): <input placeholder="Full Name2" v-model="fullName2" /><br />
  </div>

2. Define the attributes firstName and lastName in data

data() {
    
    
	return {
    
    
		firstName: '',
		lastName: '',
	}
},

3. Calculate the attribute fullName1 = firstName + lastName in computed

computed: {
    
    
      fullName1() {
    
    
           console.log('计算fullName1')
           return this.firstName + ' ' + this.lastName
       },
}

4. When modifying the data in the input corresponding to fullName2, modify the firstName and lastName values ​​at the same time. Here, the get and set methods are used.

Cut the value value and assign firstName and lastName respectively

computed: {
    
    
      fullName1() {
    
    
           console.log('计算fullName1')
           return this.firstName + ' ' + this.lastName
       },
}
fullName2:{
    
    
	get(){
    
    
		return this.firstName + " " + this.lastName
	}
	set(value){
    
    
		let names = value.split(" ")
		this.firstName = names[0]
		this.lastName = names[1]
	}
}

5. All codes

<template>
	<div>
		<div>
			姓: <input type="text" v-model="firstName">
			<br/>
			名: <input type="text" v-model="lastName">
			<br/>
			全名称:{
    
    {
    
    fullName1}}
			<br/>
			<input type="text" v-model="fullName2">
		</div>
	</div>
</template>

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				firstName: '',
				lastName: '',
			}
		},
		computed:{
    
    
			fullName1(){
    
    
				return this.firstName + " " + this.lastName
			},
			fullName2:{
    
    
				get(){
    
    
					return this.firstName + " " + this.lastName
				}
				set(value){
    
    
					let names = value.split(" ")
					this.firstName = names[0]
					this.lastName = names[1]
				}
			}
		}
	}
</script>

<style>
</style>

Guess you like

Origin blog.csdn.net/lovoo/article/details/129866988