vue自定义组件中双向绑定多个参数

前言

vue2中一个标签有且只有一个v-model,因此只能实现一个数据的双向绑定,而vue2.3+中新增了一个修饰符.sync,可以让我们在自定义组件中对多个参数进行双向绑定。

vue2中实现多个参数的双向绑定

让我们回忆一下使用v-bind模拟v-model实现双向绑定,vue2自定义组件中使用v-model,其实v-model是v-bind&v-on的语法糖,那同理.sync也是v-bind&v-on的语法糖。

v-bind实现双向绑定

//child node
Vue.component('custom-input', {
  props: {
    value: String
  },
  template: `
    <input
      v-bind:value="value"
      v-on:change="$emit('update:value', $event.target.value)"
    > `
})

//parent node
<template>
  <div>
    <custom-input 
    	:value="inputValue" 
    	@update:value="handleChangeValue"
    ></custom-input>
  </div>
</template>
<script>
  export default {
    data() {
      inputValue: "hello"
    },
    methods:{
		handleChangeValue(e){
			this.inputValue=e;
		}
	}
  }
</script>

.sync实现双向绑定

//child node
Vue.component('custom-input', {
  props: {
    value: String
  },
  template: `
    <input
      v-bind:value="value"
      v-on:change="$emit('update:value', $event.target.value)"
    > `
})

//parent node
<template>
  <div>
    <custom-input 
    	:value.async="inputValue" 
    ></custom-input>
  </div>
</template>
<script>
  export default {
    data() {
      inputValue: "hello"
    },
    methods:{
		handleChangeValue(e){
			this.inputValue=e;
		}
	}
  }
</script>

因此这里可以把.sync装饰词(:value.async="inputValue")看作是v-bind&v-on的语法糖(:value="inputValue" @update:value="handleChangeValue")。

一个标签中可包含多个.sync,使用$emit(‘update:xxx’, $event.target.value)更新props。

官网也更推荐使用.sync来代替v-model进行参数的双向绑定,在子组件中存在变更来源,便于维护

vue3中使用多个v-model

//子组件
<template>
<div>
	<input :value="username" @input="$emit('update:userpass',$event.target.value)"></input>
	<input :value="userpass" @input="$emit('update:userpass',$event.target.value)"></input>
</div>
export default {
	props:['username','userpass'],
}
</template>
//父组件
...
<custom-form v-model="username" v-model="userpass"></custom-form>
...

vue3中的v-model像是提取vue2中的.sync和v-model的优势结合,使用起来更加便捷。

vue官网 .sync 修饰符

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值