vue组件之间的关系
组件之间的关系,主要涉及到父子组件、兄弟组件之间的传值或调用对方方法的方式。
父组件向子组件传递(子组件获取父组件)
v-blind方法
父组件向子组件传递数据,在父组件里使用v-bind
绑定一个自定义的属性,在子组件中通过props
接收父组件传递的数据。
注意:
props
中的数据是只读数据
例如:
<div id="app">
<p>这是父组件数据:{{msg}}</p>
<!-- 这里v-bind绑定的自定义的属性是son,这个属性名是可以任意修改的,子组件要保持一致 -->
<login v-bind:son="msg"></login>
</div>
<script type="text/javascript">
var vm = new Vue({
el:'#app',
data:{
msg:'100'
},
components:{
login:{
template:'<div><h1>这是登录子组件</h1><h3>子组件获得的父组件数据:{{son}}</h3><h3>这里是子组件自己的数据:{{sonmsg}}</h3></div>',
// 在子组件中通过props接收父组件传递的数据
props:['son'],
data:function(){
return {
sonmsg:'50'
}
}
}
}
})
</script>
效果如图:
this.$parent方法
在子组件的方法中使用this.$parent
可以获取父组件的数据或方法
//获取parent中data里的msg的值
this.$parent.msg
//调用parent中method里的func的方法
this.$parent.func(123)
子组件向父组件传递(父组件获取子组件
v-on方法
子组件用on()或者在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件。
例如:
<body>
<div id="app">
<!-- 父组件使用子组件里的v-on监听 -->
<com2 @func="show"></com2>
</div>
<template id="tmpl">
<div>
<h1>这是子组件</h1>
<input type="button" name="" id="" value="触发父组件的方法" @click="myClick" />
</div>
</template>
<script type="text/javascript">
var com2 = {
template:'#tmpl',
data(){
return {
sonmsg:'123'
}
},
methods:{
myClick(){
console.log('触发子组件中的myclick方法')
// 触发父组件中的方法
this.$emit('func',this.sonmsg)
}
}
}
var vm = new Vue({
el:'#app',
methods:{
show(data){
console.log('触发了父组件的方法,父组件获得了数据:' + data)
}
},
components:{
com2
}
})
</script>
</body>
在上面的例子里,点击按钮后触发了子组件中的myclick
方法,myclick
执行了其中的$emit()
函数,$emit()
函数的第一个参数值是方法的名称,后面都是根据需求设定要传递的数据。在本例子中,方法名称是func
。
在子组件使用v-on绑定的自定义事件@func='show'
,事件触发了父组件中的show方法,并获得$emit
传过来的参数。
控制台输出如下:
ref方法
在子组件里使用ref
注册组件,在父组件的方法里可以使用this.$refs
获取到。
<login ref="mylogin"></login>
methods:{
get(){
console.log(this.$refs)
this.$refs.mylogin.show()
console.log(this.$refs.mylogin.msg)
}
},
components:{
login
}
控制台输出如下:
this.$children方法
在父组件的方法中使用this.$children
可以获取子组件的数据或方法
注意,和
this.parent
不同,this.$children
返回的是一个对象数组,这很好理解,一个子组件只能有一个父组件,但是一个父组件可以有多个子组件
//获取children中data里的msg的值
this.$children[0].msg
//调用children中method里的func的方法
this.$children[0].func(123)
兄弟组件之间的传递
兄弟组件之间的数据传递:bus事件总线 $emit
/$on
.
使用bus事件总线前,需要先定义全局变量
var bus = new Vue()
在第一个组件中使用$emit
发送数据
methods:{
transmit(){
// fs是自定义事件名称,son1msg是组件中的数据
bus.$emit('fs',this.son1msg)
}
}
在第二个组件中使用$on
监听对应的事件
mounted(){
// 接收组件1传递过来的数据 fs为另一个组件设置的自定义事件名
bus.$on('fs',(ret) => {
this.son2msg = ret
})
}
效果如下:
本文作者:asdio
本文链接:https://www.cnblogs.com/agitm/p/13476754.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步