.sync是一个语法糖,他应用在父子组件传值中;
在父组件中 :属性名='属性值' @update:属性名 = '属性名 = $event' 可以简写为:
: 属性名.sync = '属性值'
注意:使用.sync后,子组件中使用this.$eimt抛发出来的事件名只能是 update:属性
具体代码:
父组件
<template>
<div class="container">
<h1>父组件{{num}}</h1>
<hr>
<!-- 普通写法 -->
<!-- <myInput :num="num" @update:num = 'num = $event'/> -->
<!-- 使用.sync -->
<myInput :num.sync="num"/>
</div>
</template>
<script>
import myInput from '../components/myInput.vue'
export default {
components:{myInput},
data(){
return {
num:100
}
}
}
</script>
子组件
<template>
<div class="container">
<h1>子组件</h1>
<input type="text" :value="num" @input="handleInput">
</div>
</template>
<script>
export default {
name:'myInput',
props:{
num:{
type:Number,
require:true
}
},
methods:{
handleInput(e){
this.$emit('update:num',e.target.value/1)
}
}
}
</script>