前言
vue组件之间的关系有父子组件、同级组件以及孙父子三级关系、还有更复杂的四级、五级关系,那他们之间的数据以及方法如何传递,也就是父子组件、同级组件、孙子组件等如何调用各自的变量、方法呢?
同一组件调用
也就是在组件里调用这个组件的变量、方法
直接调用
<template>
<div>
<p>{{msg}}</p>
<button @click="test">按钮</button>
</div>
</template>
<script>
export default{
name:'HelloWorld',
data(){
return{
msg:'vue大哥,你好啊'
}
},
methods:[{
test(){
console.log("博主你真帅!")
}
}]
}
</script>
<style>
</style>
父组件调用子组件
通过$ref可以用来获取子组件的实例,从而调用子组件的方法、变量等
子组件
<template>
<div>
</div>
</template>
<script>
export default{
name:'HelloWorld',
data(){
return{
msg:'vue大哥,你好啊'
}
},
methods:{
test(){
console.log("博主你真帅!")
}
}
}
</script>
<style>
</style>
父组件
在子组件中加上ref即可通过this.$refs. . 在父组件调用子组件的方法或变量了
<template>
<div id="app">
<HelloWorld ref='hello'></HelloWorld><!-- //使用组件 -->
<button @click="getPros">按钮</button>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components:{
HelloWorld //映射组件
},
methods:{
getPros(){
this.$refs.hello.test();
alert(this.$refs.hello.msg);
}
}
}
</script>
<style>
</style>
运行效果