16.$refs和$parent和$root的使用

2021-09-06  本文已影响0人  静昕妈妈芦培培

某些情况下,我们在组件中想要直接获取到元素对象或者子组件实例:

组件实例有一个$refs属性:

App.vue

<template>
  <div>
    <h1 ref="h1">今天天气不错</h1>
    <home ref="home"></home>
    <button @click="getRefs">获取$refs</button>
  </div>
</template>

<script>
import Home from "./Home.vue";
export default {
  components: {
    Home,
  },
  data() {
    return {};
  },
  methods: {
    getRefs() {
      console.log(this.$refs.h1);
      this.$refs.home.btnClick();
      console.log(this.$refs.home.title);
      console.log(this.$refs.home.$el);
    },
  },
};
</script>

<style scoped></style>

Home.vue

<template>
  <div>
    {{ title }}
    <button @click="btnClick">按钮</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "我是home",
    };
  },
  methods: {
    btnClick() {
      console.log("点击了按钮");
    },
  },
};
</script>

<style scoped></style>

image.png

$parent$root

可以在子组件中通过$parent访问父组件,通过$root访问根组件
注意:在Vue3中已经移除了$children的属性,所以不可以使用了。

<template>
  <div>
    {{ title }}
    <button @click="btnClick">按钮</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "我是home",
    };
  },
  methods: {
    btnClick() {
      console.log("点击了按钮");
      console.log(this.$parent)
      console.log(this.$root)
    },
  },
};
</script>

<style scoped></style>

此文档主要内容来源于王红元老师的vue3+ts视频教程

上一篇 下一篇

猜你喜欢

热点阅读