sync
在vue2.4以前,父组件向子组件传值用props;子组件不能直接更改父组件传入的值,需要通过$emit触发自定义事件,通知父组件改变后的值。比较繁琐,写法如下:
//父组件
<template>
<div class="parent">
<p>父组件传入子组件的值:{{name}}</p>
<fieldset>
<legend>子组件</legend>
<child :val="name" @update="modify">
</child>
</fieldset>
</div>
</template><script>
import Child from './Child'
export default {
components:{Child},
data () {
return {
name:'linda'
}
},
methods:{
modify(newVal){
this.name=newVal
}
}
}
</script>
//子组件
<template>
<label class="child">
输入框:
<input :value=val @input="$emit('update',$event.target.value)"/>
</label>
</template>
<script>
export default {
props:['val']}
</script>
vue2.4以后的写法明显舒服许多,上面同样的功能,直接上代码
//父组件
<template>
<div class="parent">
<p>父组件传入子组件的值:{{name}}</p>
<fieldset>
<legend>子组件</legend>
<child :val.sync="name">
</child>
</fieldset>
</div>
</template><script>
import Child from './Child'
export default {
components:{Child},
data () {
return {
name:'linda'
}
}
}
</script>
//子组件
<template>
<label class="child">
输入框:
<input :value=val @input="$emit('update:val',$event.target.value)"/>
</label>
</template>
<script>
export default {
props:['val']}
</script>
写法上简化了一部分,很明显父组件不用再定义方法检测值变化了。其实只是对以前的$emit方式的一种缩写,.sync其实就是在父组件定义了一update:val方法,来监听子组件修改值的事件。
$attrs
想象一下,你打算封装一个自定义input组件——MyInput,需要从父组件传入type,placeholder,title等多个html元素的原生属性。此时你的MyInput组件props如下:
props:['type','placeholder','title',...]很丑陋不是吗?$attrs专门为了解决这种问题而诞生,这个属性允许你在使用自定义组件时更像是使用原生html元素。比如:
//父组件
<my-input placeholder="请输入你的姓名" type="text" title="姓名" v-model="name"/>










