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

    Home.vue

    <template>
    <div id="home">
      <!--<v-header :_title="title" :homemsg="msg" :homerun="run" :_home="this"></v-header>-->
      <!--<v-header :_title="title" ></v-header>-->
    
      <v-header ref="header"></v-header>
      首页组件
    
      <button @click="getChildData()">获取子组件的数据和方法</button>
    </div>
    </template>
    
    <script>
      /* 父组件给子组件传值
        1、父组件调用子组件的时候,动态绑定属性  <v-header :_title="title"></v-header>
        2、在子组件里面通过props接收父组件传过来的数据
          props:["_title"]
    
          props:{"_title" :"String"}
    
        3、直接在子组件里面使用
    
    
      父组件主动获取子组件的数据和方法
        1、调用子组件的时候定义一个ref
        <v-header ref="header"></v-header>
    
        2、在父组件里面通过
          this.$ref.header.属性
          this.$ref.header.方法
    
    
      子组件主动获取父组件的数据和方法
              this.$parent.数据
              this.$parent.方法 */
    
    
    
      import Header from './Header.vue';
    
        export default {
            name: "Home",
            data(){
              return {
                // msg:'我是一个Home组件',
                title:"asddd",
                msg:'我是home组件'
              }
            },
          methods:{
              run(){
                console.log('这是父组件的run方法' )
              },
              getChildData(){
                console.log(this.$refs)
                console.log(this.$refs.header.msg)
                this.$refs.header.run()
              }
          },
          components: {
              'v-header' :Header
          }
        }
    </script>
    
    <style scoped>
    
    </style>
    

      Header.vue

    <template>
      <div>
        <h2>这是头部组件</h2>
        <!--<button @click="homerun('123')">执行父组件的方法</button>-->
        <!--<button @click="getParent()">获取父组件的数据和方法</button>-->
    
        <button @click="getParentData()">获取父组件的数据和方法</button>
    
      </div>
    </template>
    
    <script>
      export default {
        name: "Header",
        data() {
          return {
            msg:'子组件的msg'
          }
    
        },
        methods: {
          run(){
            console.log('我是子组件的run方法')
          },
          getParentData(){
            /*子组件主动获取父组件的数据和方法
              this.$parent.数据
              this.$parent.方法 */
            // console.log(this.$parent.msg)
            this.$parent.run() //调用父组件的run方法
          }
    
    
        },
    
      }
    </script>
    
    <style scoped>
    
    </style>
    

      运行结果

  • 相关阅读:
    intellij idea 为JavaEE项目建立Servlet
    DNS无响应
    取消Gridvie中button的焦点
    android.os.NetworkOnMainThreadException
    java.net.MalformedURLException: Protocol not found:
    Failure [INSTALL_FAILED_OLDER_SDK]
    android library projects cannot be launched
    CDQ分治的嵌套
    CDQ分治入门
    最远 Manhattan 距离
  • 原文地址:https://www.cnblogs.com/malong1992/p/12133608.html
Copyright © 2011-2022 走看看