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

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

一、ref(但不能实时更新获取)

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

<child ref="headerChild"></child>

2.在父组件里面通过

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

二、$emit() (可以动态实时更新获取)

子组件中定义 this.$emit('data', times);

<child
@data="getData"><child> 父组件中 getData(tiems) 得到;

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

在子组件里面通过

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 获取子组件的数据,this.$refs 只能放在方法里面获取子组件的数据,而不能作为参数
     },
     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>

或者子组件获取父组件的数据和方法,并且随着父组件实时更新数据(用到watch) 

//父组件 --- header.vue
<template>
  <div id="header">  
    <child-template ref="childTemplate" :commentList = dataList></child-template>    //注意:ref 的 childTemplate 是随便定义的,与下面的 this.$refs.childTemplate 保持一致 ;用v-bind 绑定子组件的 commentList ,将值 dataList 传给子组件     
    <button @click="getChild()">父组件获取子组件的数据和方法</button>
  </div>
</template>
<script>
import Child from './child'    // import 子组件 child.vue
export default {
  data () {
      return {
          title:'我是父组件的数据',
      dataList:[{"id":1,"name":"liuqing"}]
} }, methods: { getChild (){ console.log(this.$refs.childTemplate.name) //this.$refs.childTemplate 获取子组件的数据,this.$refs 只能放在方法里面获取子组件的数据,而不能作为参数 }, 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"
 props:{
  commentList:{
    type:Array //获取的父组件的 commentList 是一个数组
  }
 }, data () {
return { name:'我是子组件里面的数据' } },
 watch:{
  commentList:{
    handler(newValue,oldVlaue){
      console.log(newValue) //newVlaue 等于 获取父组件的 dataList 的值,并能随着父组件 dataList 的变化而实时变化
    },
    deep:true
  }
 }, methods:{
} } </script>
原文地址:https://www.cnblogs.com/liuqing576598117/p/9916291.html