首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue 在父(子)组件引用其子(父)组件方法和属性

Vue 在父(子)组件引用其子(父)组件方法和属性

作者头像
授客
发布2020-06-23 13:59:06
1.8K0
发布2020-06-23 13:59:06
举报
文章被收录于专栏:授客的专栏授客的专栏

Vue 在父(子)组件引用其子(父)组件方法和属性

by:授客 QQ:1033553122

开发环境

Win 10

element-ui "2.8.2"

Vue 2.9.6

父组件代码

<template>

<div>

<button @click="callChildMethod()">父组件调用子组件方法</button>

<button @click="getChildAttribute()">父组件获取子组件属性</button>

<header-part ref="headerChild"></header-part>

</div>

</template>

<script>

import HeaderPart from "./HeaderPart";

export default {

components: {

HeaderPart

},

data() {

return {

title: "父组件"

};

},

methods: {

callChildMethod() {

console.log("父组件中调用子组件printName方法");

this.$refs.headerChild.printName();

},

getChildAttribute() {

console.log(

"父组件获取子组件title属性值:" + this.$refs.headerChild.title

);

},

printName() {

console.log("打印父组件title属性值:" + this.title);

}

},

mounted() {

this.$customUtils.headerMenu.initMenuComponent();

}

};

</script>

子组件代码

<template>

<div>

<button @click="callFatherMethod()">子组件中调用父组件的方法</button>

<button @click="getFatherAttribute()">子组件中获取父组件的属性</button>

</div>

</template>

<script>

export default {

data() {

return {

title: "子组件"

};

},

methods: {

callFatherMethod() {

console.log("子组件中调用父组件printName方法")

this.$parent.printName();

},

getFatherAttribute(){

console.log("子组件获取父组件title属性值:" + this.$parent.title);

},

printName(){

console.log("打印子组件title属性值:" + this.title)

}

}

};

</script>

实验结果:

总结

父组件获取中引用子组件方法、属性

给子组件定义一个ref(假设名称为childRef),然后父组件中通过this.$refs.childRef获取子组件,进而引用子组件方法、属性,如下:

this.$refs.childRef.方法(参数列表)

this.$refs.childRef.属性

子组件中获取父组件的方法、属性

在子组件里面通过this.$parent获取父组件,进而引用父组件的方法和属性,如下:

this.$parent.属性

this.$parent.方法

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-06-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 开发环境
  • 父组件代码
  • 子组件代码
  • 实验结果:
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档