前言
vue组件之间的关系有父子组件、同级组件以及孙父子三级关系、还有更复杂的四级、五级关系,那他们之间的数据以及方法如何传递,也就是父子组件、同级组件、孙子组件等如何调用各自的变量、方法呢?
子组件调用父组件的变量
1.父组件
在字标签里说明,menus属性要引用的是父组件定义的menus数组
<template>
<div id="app">
<Menu :menus='menus'></Menu><!-- 在字标签里说明,menus属性要引用的是父组件定义的menus数组 -->
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import Menu from './components/Menu.vue'
export default {
name: 'App',
components:{
HelloWorld, //映射组件
Menu
},
data(){
return{
menus:[
{
name:'Java',
url:'#'
},
{
name:'C',
url:'#'
},
{
name:'C++',
url:'#'
},
{
name:'Python',
url:'#'
}
]
}
}
}
</script>
<style>
</style>
子组件
在子组件里声明接收属性,这样接收的属性就会成为组件对象的属性了,就可以在组件内自由使用了
<template>
<div>
<ul>
<li v-for="(menu,index) in menus" :key='index'>
<a href='menu.url'>
{{menu.name}}
</a>
</li>
</ul>
</div>
</template>
<script>
export default{
name:'Menu',
props:['menus']//声明接收menus属性,这个属性就会成为组件对象的属性了
}
</script>
<style>
</style>
子组件调用父组件的方法函数
子组件调用父组件的方法函数有三种
1.第一种
父组件把方法传入子组件中,在子组件里直接调用这个方法
父组件
在父组件的字标签绑定属性,说明这个属性引用那个方法
<template>
<div id="app">
<Child :say='say'></Child>
</div>
</template>
<script>
import Child from './components/Child.vue'
export default {
name: 'App',
components:{
Child //映射组件
},
methods:{
say(){
alert('博主你最帅!')
}
}
}
</script>
<style>
</style>
子组件
在子组件通过props声明接收并直接调用方法
<template>
<button @click="say">世界上最帅的人?</button>
</template>
<script>
export default{
name:'Child',
props:['say']
}
</script>
<style>
</style>
2.第二种
直接在子组件中通过this.$parent.event来调用父组件的方法
父组件
<template>
<div id="app">
<Child ></Child>
</div>
</template>
<script>
import Child from './components/Child.vue'
export default {
name: 'App',
components:{
Child //映射组件
},
methods:{
say(){
alert('博主你最帅!')
}
}
}
</script>
<style>
</style>
子组件
<template>
<button @click="say">世界上最帅的人?</button>
</template>
<script>
export default{
name:'Child',
methods:{
say(){
this.$parent.say();
}
}
}
</script>
<style>
</style>
3.第三种
在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
父组件
<template>
<div id="app">
<Child @say='say()'></Child>
</div>
</template>
<script>
import Child from './components/Child.vue'
export default {
name: 'App',
components:{
Child //映射组件
},
methods:{
say(){
alert('博主你最帅!')
}
}
}
</script>
<style>
</style>
子组件
<template>
<button @click="test">世界上最帅的人?</button>
</template>
<script>
export default{
name:'Child',
methods:{
test(){
this.$emit('say');
}
}
}
</script>
<style>
</style>