前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >12.父组件主动获取子组件的数据和方法

12.父组件主动获取子组件的数据和方法

作者头像
玩蛇的胖纸
发布2019-10-14 14:59:46
1.4K0
发布2019-10-14 14:59:46
举报

父组件主动获取子组件的数据和方法

1.父组件Home.vue

代码语言:javascript
复制
<template>
    <div>
        <h2>{{msg}}</h2>
        <!-- 1.调用子组件的时候调用一个ref -->
        <!-- 2.在父组件中通过this.$refs.header.数据 this.$refs.header.方法 调用子组件的数据和方法 -->
        <!-- 注意,第一步是ref,第二步是refs -->
        <v-header ref="header"></v-header>
        <button @click="getData()">获取子组件数据</button>
        <button @click="getFunction()">获取子组件的方法</button>
    </div>
</template>
<script>
import Header from "./Header.vue";
export default {
  name: 'home',  
  data () {
    return {
        msg:'首页组件',
    }
  },
  methods:{
    getData(){
      alert(this.$refs.header.msg)
    },
    getFunction(){
      this.$refs.header.run()
    }
  },
  components:{
    'v-header':Header
  }
}
</script>
<style lang="scss" scoped>
h2{
    color: red;
}
</style>

2.子组件Header.vue

代码语言:javascript
复制
<template>
    <div>
        <h2>{{msg}}</h2>
    </div>
</template>
<script>
export default {
  name: 'Header',  
  data () {
    return {
        msg:'头部组件',
        title:'子组件'
    }
  },
  methods:{
      run(){
          alert('子组件run方法')
      }
  }
}
</script>
<style lang="scss" scoped>
h2{
    color: green;
}
</style>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 父组件主动获取子组件的数据和方法
    • 1.父组件Home.vue
      • 2.子组件Header.vue
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档