组件之间的传值?
在vue中,父子组件的关系可以总结为prop向下传递,事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件给父组件发送信息。
- 父组件传值给子组件,通过props属性进行传递。
- 子组件给父组件传值,通过的是$emit方法,第一个参数是自定义事件的名字,第二个参数是传递过来的值,如果传递过来的值很多,可以使用对象的方法,把它们都写在第二个参数中。
- 兄弟组件传值,在vue原型上定义一个新的实例,然后采用 e m i t 和 emit和 emit和on这两个方法进行获取传递过来的值。
- 给后代组件传值,provide和inject方法。
<!-- App.vue -->
<template>
<div id="App">
<Father></Father>
</div>
</template>
<script>
import Father from '@/components/test/Father'
export default {
name: 'App',
comments:{
Father
}
}
</script>
<!-- Father.vue -->
<template>
<div class="father">
<h1>父亲组件</h1>
<Children :count="count" @sayLove="getLove"></Children>
<span>子组件向父组件传过来的值----{{mylove}}</span>
<Brother></Brother>
</div>
</template>
<script>
import Brother from '@/components/test/Brother'
import Children from '@/components/test/Children'
export default {
provide(){
return{
father:this //给后代接受
}
},
data(){
return{
count:1,
mylove:""
}
},
comments:{
Children,
Brother
},
methods:{
getLove(e){
console.log(e);
this.mylove=e;
}
}
}
</script>
<!-- Children.vue -->
<template>
<div class="children">
<h2>儿子组件</h2>
<span>父亲组件传过来的值--{{count}}</span>
<Grandson></Grandson>
<button @click="sayLove">表达爱意</button>
</div>
</template>
<script>
import Grandson from '@/components/test/Grandson'
export default {
props:['count'],
comments:{
Grandson
},
methods:{
sayLove(){
this.$emit('sayLove','I love you')
this.$bus.$emit('sayLoveToBro','I love you brother')
}
}
}
</script>
<!-- Brother.vue -->
<template>
<div>
<h2>兄弟组件</h2>
</div>
</template>
<script>
export default {
created () {
this.$bus.$on('sayLovToBro',this.getlove)
},
methods:{
getlove(e){
console.log("兄弟组件",e)
}
}
}
</script>
<!-- Grandson.vue -->
<template>
<div>
<h3>孙子组件</h3>
<span>爷爷给的值----{{count}}</span>
</div>
</template>
<script>
export default {
inject:['father'],
data(){
return{
count:this.father.count
}
}
}
</script>