*Vue 父子组件传值在其他文章已详细介绍:https://blog.csdn.net/qq_42540989/article/details/98481824
本文介绍的是一种更加方便的写法
1、建议先看官方文档:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6
2、父组件
// 父组件
<template>
<div class="hello">
<son :num.sync="num"></son>
<h1>我是父组件(接收子组件改变的值)======{{num}}</h1>
</div>
</template>
<script>
import son from './son'
export default {
name: 'HelloWorld',
data () {
return {
msg: '我是父组件',
num:1
}
},
components: {
son
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
3、子组件
// 子组件
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="change()">{{sonNum}}</button>
</div>
</template>
<script>
export default {
name: 'son',
props: ['num'],
data(){
return {
sonNum: 1,
msg:'我是子组件'
}
},
created(){
this.sonNum = this.num
},
methods:{
fn(){
this.sonNum++
this.$emit('update:num',this.sonNum);
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
4、简单介绍:
*以前prop实现双向绑定,采用的方法是:子组件向父组件发送一个事件,父组件监听到传过来的事件,然后更新prop。
为了方便起见,我们为这种模式提供一个缩写,即 .sync
修饰符:
①组件内以 update:myPropName
的模式触发事件取而代之。(例如:this.$emit('update:num',this.sonNum))
②父组件 v-bind:value 加上.sync修饰符,即 :value.sync(例如: :num.sync="num")
6、当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync
修饰符和 v-bind
配合使用:
// v-bind.sync="对象"
<text-document v-bind.sync="doc"></text-document>
这样会把 doc 对象中的每一个属性 (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。
7、 * 例如:这是 v-bind:title.sync=”doc.title + ‘!’”
是无效的,因为带有 .sync
修饰符的 v-bind
不能和表达式一起使用。
8、 *详细介绍,官方文档中都已经说明。建议可以亲自手写实践一下,加深记忆。