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

Posted liuqing576598117

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 获取子组件的数据,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>

 


















以上是关于vue 的父组件和子组件互相获取数据和方法的主要内容,如果未能解决你的问题,请参考以下文章

Vue 的父组件和子组件生命周期钩子执行顺序

Vue 的父组件和子组件生命周期钩子函数执行顺序?

Vue 的父组件和子组件生命周期钩子函数执行顺序?

Vue-的父组件和子组件生命周期钩子函数执行顺序

Vue 的父组件和子组件生命周期钩子执行顺序

Vue 的父组件和子组件生命周期钩子执行顺序是什么