vue(16)父子组件之间直接相互访问

父子组件之间可以直接调用对方的方法和变量

父组件:

<template>
    <div>
      <button @click="parentClick">父组件按钮</button>
      <HelloWorld ref="firstChild"></HelloWorld>//给子组件起一个别名叫firstChild,因为父组件会有多个子组件需要别名来区分到底访问哪一个子组件的数据
    </div>
</template>

<script>
import HelloWorld from './component/HelloWorld'

export default {
   name:"App",
   data:function(){
       return {
        parentCount:1
       };
   },
   components:{
       HelloWorld
   },
   computed:{
       
   },
   methods:{
      parentFun(){
        console.log('this is parent component');
      },
      parentClick(){
        console.log(this.$refs.firstChild.childCount);//访问子组件的变量
        this.$refs.firstChild.childFun();//调用子组件的方法
      }
   }
}
</script>

<style scoped>
</style>

子组件:

<template>
<div>
    <button @click="childClick">子组件按钮</button>
</div>
</template>

<script>
export default ({
    data:function(){
        return{
            childCount:2
        }
    },
    methods:{
        childClick(){
            console.log(this.$parent.parentCount);//访问父组件的变量
            this.$parent.parentFun();//调用父组件的方法
   //这里可以用 this.$parent.$parent...继续访问父组件的父组件...,可以使用this.$root访问根组件的数据
        },
        childFun(){
            console.log('this is child component');
        }
    }
})
</script>

<style scoped>

</style>
原文地址:https://www.cnblogs.com/maycpou/p/14736768.html