关于vue父子组件传值问题以及隔代组件传值(即爷孙组件)
今看到一篇关于vue传值的文章,遂记下。共勉之!
/* * 父组件界面写法 */ <template> <div id="home"> <child :sendDataToChid="words" :sendSecondData="moreWords" @fromSon="fromSon"> </child> <p>{{fromSonData}}</p>
</div> </template> <script> import Child from '@/components/child.vue' export default { name:'home', data(){ return{ words:'从父组件过去的数据哦', moreWords:'多个数据也可以传递哦', fromSonData:'现在啥都没有哦', } },
components:{
Child
}, methods:{ //接收从子组件传递过来的数据 fromSon(data){ this.fromSonData = data; } } } </script>
<style>
/**这里写样式哦**/
</style>
/* * 子组件界面写法 */ <template> <div id="child"> <p>{{sendDataToChid}}</p> <p>{{sendSecondData}}</p> <button @click="sendDataToFather"> 点击按钮就可以向父组件 传递值了 </button> </div> </template> <script> export default{ name:'child', props:['sendDataToChid','sendSecondData'], data(){ return(){ } }, methods:{ sendDataToFather(){ let greetWords = 'hello world!'; this.$emit('fromSon',greetWords ) } } } </script>
<style>
/**这里写样式哦**/
</style>
父组件向子组件传值方式就是通过 props 属性,子组件通过 props 属性接收从父组件传过来的值,而父组件传值的时候使用 v-bind 将子组件中预留的变量名绑定为 data 里面的数据即可。
子组件向父组件传值方式就是用了 this.$emit 来遍历 fromSon 事件 ,首先用按钮来触发 sendDataToFather 事件,在 sendDataToFather 中用 this.$emit 来遍历 fromSon 事件,最后返回 this.fromSonData 值。
简短总结:
子组件中需要以某种方式 例如点击事件的方法来触发一个自定义事件,
将需要传递的值作为 $emit 的第二个参数,该值将作为实参传递给响应自定义事件的方法,
在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听。
。
。
。
第二弹来了
就是,父组件需要点击某个按钮触发事件后,再改变子组件的界面相关内容。代码如下:
给子组件写一个ref属性,父组件可以通过ref拿到子组件中的数据和方法,这样在父组件中就可以触发子组件的事件了。父组件向子组件传参通过prop属性。
父组件:
<div>
<children ref="children" :content="content"></children>
<button @click="handleSubmit">点击</button>
</div>
//js
handleSubmit(){
this.$refs.children.updateList();
}
子组件:
<template>
<div>children</div>
</template>
//js
export default{
props:{
content:{
type:String,
}
},
data(){
return{
text:'hello world'
}
},
methods:{
updateList(){
console.log('hello world');
}
}
}
数据传递用prop,事件调用用ref。
关于爷孙组件传值需要用到 : $attrs 以及 $listeners
$attrs 是 vue 实例的属性。
具体操作流程如下:
A (父组件) => B(子组件) => C(孙组件)
组件A
<template>
<div class="container">
<zujianb :num="num" @reciveThing="fromC"></zujiainb>
</div>
</template>
<script>
import zujianb from './zujianb'
export default{
components:{ zujianb },
data(){
return{
num:10
}
},
methods:{
fromC(val){
console.log(val);//我是C组件传递过来的数据 => hello A
console.log('阿西吧,可以接收到孙组件传递过来的数据耶=>from C组件')
}
}
}
</script>
组件 B
<template>
<div class="container">
<zujianc v-bind="$attrs" v-on="$listeners"></zujianc>
</div>
</template>
<script>
import zujianc from './zujianc'
export default{
props:{},
inheritAttrs:false,
components:{ zujianc },
created(){
console.log(this.$attrs); //打印出传递过来的值 num
console.log(this.$listeners);//打印出方法 reviceThing
}
}
</script>
组件C
<template>
<div class="container">
<el-button @click="contactA">点击可以触发 A组件 的事件</el-button>
</div>
</tempalte>
<script>
export default{
data(){
return(){
}
},
methods:{
contactA(){
this.$listeners.reciveThing('hello A');
}
}
}
</script>
//至此,爷孙传值就解决了耶
参考链接:https://segmentfault.com/a/1190000021432732
如果快乐太难,那祝你平安。