在Vue中,子父组件最常用的通信方式就是通过props进行数据传递,props值只能在父组件中更新并传递给子组件,在子组件内部,是不允许改变传递进来的props值,这样做是为了保证数据单向流通。但有时候,我们会遇到一些场景,需要在子组件内部改变props属性值并更新到父组件中,这时就需要用到
.sync修饰符。
定义一个Child子组件并设置name属性来显示一句欢迎语。 当点击按钮时,通过在父组件中来改变name属性的值;当点击欢迎语时,则通过在Child子组件中改变name属性值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>.sync</title>
</head>
<body>
<div id="app">
<child :name.sync="name"></child>
<button type="button" @click="changePropsInFather">在父组件中将props值改变为'props'</button>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
// 定义一个子组件
Vue.component('Child', {
template: `<h1 @click="changePropsInChild">hello, {{name}}</h1>`,
props: {
name: String,
},
methods:{
changePropsInChild(){
this.$emit('update:name', 'I am from child');
}
},
})
// 实例化一个Vue对象
const app = new Vue({
el: '#app',
data(){
return {
name: 'world'
}
},
methods:{
changePropsInFather(){
this.name='I am from father'
},
},
})
</script>
</body>
</html>
当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。
:name.sync就是:name="name" @update:name="name = $event"的缩写。