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()调用子组件的方法

  • 相关阅读:
    vim 命令替换重复命令
    Python环境安装
    MySQL 查看show profile
    XSS攻击与CSRF攻击与防御
    HTTPS的原理
    PHP curl的请求步骤
    【论文阅读】HRNet
    【学习笔记】gRPC-python
    【Linux学习笔记】Linux基础
    【Golang学习笔记】入门:结构体、方法与接口
  • 原文地址:https://www.cnblogs.com/toughy/p/11841474.html
Copyright © 2011-2022 走看看