zoukankan      html  css  js  c++  java
  • vue 父子组件的相互调用

    1.子组件直接调用父组件的数据和方法

    在父组件father.vue

    点击查看代码
    <template>
      <div>
        <!-- 父组件里面的数据 -->
        <p>父组件里面的数据{{data}}</p>  
    
        <!-- 父组件里面的方法 -->
        <p click="test">父组件里面的方法方法方法方法</p>
        <!-- 使用组件 -->
        <child></child>
      </div>
    </template>
    
    <script>
    import child from './components/child.vue'// 引入子组件
    export default {
      components:{
        //注册组件 
        child
      },
      data(){
        return{
          data:'我的父组件data'
        }
      },
      methods:{
        test(){
          console.log('点击了父组件')
        }
      }
    }
    </script>
    
    下面在子组件中调用父组件的数据和方法
    点击查看代码
    <template>
      <div>
        <button @click="toFather">我是子组件  {{this.$parent.data}}</button>
        <!-- this.$parent.data获取父组件的数据 -->
      </div>
    </template>
    <script>
    export default {
      data(){
        return{}
      },
      methods:{
        toFather() {
          // 直接通过this.$parent.test()获取方法
          this.$parent.test()
        }
      }
    }
    </script>
    

    总结:
    直接在子组件中this.\(parent.prop调用的数据; this.\)parent.fn()调用的方法

    2.父组件直接调用子组件的数据和方法

    父组件调用子组件的地方,添加一个ref的属性,属性值任意定义 即在父组件组件中 father.vue

    点击查看代码
    <template>
      <div>
        我是父组件
        <!--调用子组件组件  添加ref属性 -->
        <child ref="getdata"></child>    
        <button @click="getChild">点击按钮获取子组件的数据msg</button>
      </div>
    </template>
    <script>
    import child from './components/child.vue'// 引入子组件
    export default {
      components:{
        //注册组件 
        child
      },
      data(){
        return{
        }
      },
      methods:{
        getChild(){
          // this.$refs.getdata.msg 拿到数据
          console.log(this.$refs.getdata.msg)
        }
      }
    }
    </script>
    

    child.vue的数据

    点击查看代码
    <template>
      <div>
        <button>我是子组件</button>
      </div>
    </template>
    <script>
    export default {
      data(){
        return{
          msg:'我是子组件数据'
        }
      },
      methods:{
      }
    }
    </script>
    

    总结:父组件调用子组件的地方,添加一个ref的属性,属性值任意定义
       父组件某一个事件中,可以通过this.\(refs.test.prop拿到子组件的数据,可以通过this.\)refs.test.fn()调用子组件的方法

    目前还在学习中,希望会对大家有所帮助,觉得不错,就点赞支持一下。 另外,转载时请附带链接。谢谢!
  • 相关阅读:
    无题
    静心
    随笔
    skynet1.0阅读笔记2_skynet的消息投递skynet.call
    skynet1.0阅读笔记_skynet的启动
    Mysql: Connect/C++ 使用过程中发现返回 std::string 造成的内存泄露
    MySql C++调用库Connector/c++编译 和 接口封装【三】Connector/c++ 使用总结及封装
    MySql: ”Commands out of sync“Error (Connect/C++)
    Connector/c++ 查询Mysql,出现 can't fetch because not on result set 错误
    mysql 修改密码
  • 原文地址:https://www.cnblogs.com/dangkai/p/15766704.html
Copyright © 2011-2022 走看看