vue 的父组件和子组件互相获取数据和方法

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

1.调用子组件的时候 定义一个ref

<headerchild ref="headerChild"></headerchild>

2.在父组件里面通过

this.$refs.headerChild.属性
this.$refs.headerChild.方法

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

在子组件里面通过

this.$parent.属性
this.$parent.方法

演示代码:

//父组件 --- header.vue
<template>
  <div id="header">  
    <child-template ref="childTemplate"></child-template>    //注意:ref 的 childTemplate 是随便定义的,与下面的 this.$refs.childTemplate 保持一致
    <button @click="getChild()">父组件获取子组件的数据和方法</button>
  </div>
</template>
<script>
import Child from './child'    // import 子组件的 child.vue
export default {
  data () {
      return {
          title:'我是父组件的数据'
      }
  },
  methods: {
     getChild (){
         console.log(this.$refs.childTemplate.name)        //this.$refs.childTemplate 获取自逐渐
     },
     run (){
         console.log("我是父组件里面的方法")
     }
  },
  components: {
      'child-template': Child   //和 import 的 对应
  }
}
</script>
//子组件 --- child.vue
<template>
  <div id="child">
      <button @click="getParent()">获取父组件的数据和方法</button>
  </div>
</template>
<script>
export default {
 name:"ChildTemplate" data () {
return { name:'我是子组件里面的数据' } }, methods:{ getParent(){ console.log(this.$parent.title) /*获取整个父组件*/ this.$parent.run()/*获取父组件的方法*/ } }, props:['title','run','home'] /*通过props接收父组件传递过来的数据 */ } </script>

猜你喜欢

转载自www.cnblogs.com/liuqing576598117/p/9916291.html