zoukankan      html  css  js  c++  java
  • 12.父组件主动获取子组件的数据和方法

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

    1.父组件Home.vue

    <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

    <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>
  • 相关阅读:
    shell lab
    cache lab
    后缀树
    leetcode maximum-length-of-repeated-subarray/submissions
    leetcode assign-cookies
    lcs
    leetcode delete-operation-for-two-strings
    【C】C语言typedef
    【C】C语言结构体指针的语法
    【JAVA】Java 命令行参数解析
  • 原文地址:https://www.cnblogs.com/xuepangzi/p/11666310.html
Copyright © 2011-2022 走看看