Vue3中的$refs、$parent、$root的使用方法

1.父组件访问子组件:vue3使用的是$refs,vue2中使用的是$children,但在vue3中给废弃掉了。

<template>
  <div>
    <div >
  <!-- 在子组件上定义ref -->
  <son :ac="name" :nn="456" ref="son"></son>
  <!-- 在标签上定义ref -->
  <p ref="p">p标签</p>
  </div>
  </div>
</template>

//在生命周期中打印一下访问的值
 mounted(){
    console.log(this.$refs.son.a,this.$refs.p);
  }

2.子组件访问父组件:$parent在开发中尽量少用,因为组件复用性很高,耦合性较差。

mounted(){
  console.log(this.$parent);
  
}

3.子组件访问根组件

mounted(){
  console.log(this.$root);
}

猜你喜欢

转载自blog.csdn.net/qq_72760247/article/details/128645730