1.父子组件传值($parent / $ref)
父组件
<template>
<div>
<div>{{msg}}</div>
<child ref="children"></child>
<button @click="change">点击改变子组件值</button>
</div>
</template>
<script>
export default {
data() {
return {
fatherMsg: 'Welcome'
}
},
methods: {
change() {
this.$ref.children.message = '父改子值'
}
}
}
</script>
子组件
<template>
<div>
<span>{{message}} </span>
<p>获取父组件的值为: {{parentVal}}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Vue'
}
},
computed:{
parentVal(){
return this.$parent.fatherMsg;
}
}
}
</script>
2.全局事件传值($emit / $on)
3.【重要】祖孙组件传值($attrs)
A是B组件的父组件,B是C组件的父组件。想要组件A直接给C组件传递数据
祖组件
<template>
<div class="section">
<Father :sendGrandSon="sendGrandSon" :sendSon="sendSon" @change1="changFromSon" @chang2="changFromGrandSon"></Father>
</div>
</template>
<script>
export default {
name: 'Grandfather',
data() {
return {
msg: '我是祖',
sendSon:'传给子',
sendGrandSon:'传给孙'
}
},
methods(){
changFromSon(value){
console.log('子传值过来',value)
},
changFromGrandSon(value){
console.log('孙传值过来',value)
}
}
}
</script>
父组件
<template>
<div>
<Son v-bind="$attrs" v-on="$listeners"></Son>
<el-button @click="click">给父发消息</el-button>
</div>
</template>
<script>
export default {
name: 'Father',
props:['sendSon'],
data() {
return {
msg: '我是祖'
}
},
methods(){
click(){
this.$emit('changFromSon','我是子')
}
}
}
</script>
孙组件
<template>
<div>
<div class="section">我是孙</div>
<el-button @click="click">给爷爷发消息</el-button>
</div>
</template>
<script>
export default {
name: 'Son',
created(){
console.log(this.$attrs)
},
methods(){
click(){
this.$emit('changFromGrandSon','我是孙')
}
}
}
</script>
注意:
祖孙传值的参数,不能在父组件(中间层)使用props接受参数。