脚本宝典收集整理的这篇文章主要介绍了vue2 基础学习04 (Vue组件:父子组件之间的通信),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
一个简单的例子
如图,下面有个目录结构:父组件下面有个子组件。
我们要实现的就是:
- 子组件接受父组件的data数据
- 点击子组件中按钮,可以将子组件中数据反馈给父组件
直接上代码:这里没有引入vue,自行引入@H_777_25@
<div id="app"></div>
<script>
//子组件
var child = {
template: `
<div class="child">
子组件---> {{fromfather}} <br >
<button @click='sendParent'>反馈信息给父组件</button>
</div>
`,
props: ['fromfather'],
data(){
return{
childmsg:'我是子组件的数据'
}
},
methods: {
sendParent() {
this.$emit('fromchild', this.childmsg)
}
}
}
// 父组件
var parent = {
template: `<section>
父组件 ----> {{fromchildmsg}}
<child v-bind:fromfather="msg" @fromchild='getdata'></child>
</section>
`,
//声明子组件
components: {
child
},
//父组件的数据,准备让子组件接受
data() {
return {
msg: '我是父组件的数据',
fromchildmsg:''
}
},
methods: {
getdata(val) {
this.fromchildmsg = val
}
}
}
new Vue({
el: '#app',
components: {
parent
},
template: `
<div>
<parent class="parent"></parent>
</div>
`
})
</script>
点击后效果如图:
箭头后面的即是从其他组件中传过来的数据
父传子
props:['属性名']
来接收收到就是自己的了,随便你用
子传父
$emit('自定义事件名',变量1,变量2)
触发@自定义事件名=‘事件名’
监听如:
子组件方法里 this.$emit('sendfather',val1,val2)触发自定义事件
父组件里 <child @sendfather='mymethods'></child>
以上是脚本宝典为你收集整理的vue2 基础学习04 (Vue组件:父子组件之间的通信)全部内容,希望文章能够帮你解决vue2 基础学习04 (Vue组件:父子组件之间的通信)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。