vue3+ts学习(二十一):引用元素和组件的方法

56 阅读1分钟

在vue中是不推荐dom操作的,不过vue还是提供了一种获得元素对象和组件实例的方法

父组件,$refs作用于元素则获取该元素标签,作用于组件,则获得组件实例。这个在表单验证的时候用的较多

<template>
  <div>
    <h1 ref="title">{{ message }}</h1>
    <button @click="clickBtn">获取h1元素</button>
    <Message ref="com"></Message>
  </div>
</template>

clickBtn() {
      console.log("拿到ref为title的标签:", this.$refs.title);
      console.log("$el只能作用于子组件的ref,拿到根元素,也就是最外层div:", this.$refs.com.$el);
      console.log("拿到的是组件实例,也就是子组件的this,自然可以访问data里的数据:", this.$refs.com.message);
    }

子组件,$parent和$root可以分别获得父组件和根组件实例,用的较少了解即可。

<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="clickBtn">点击message组件</button>
  </div>
</template>

clickBtn(){
      console.log("获取父组件的组件实例,用的较少:", this.$parent);
      console.log("获取根组件的组件实例,用的较少:", this.$root);
    }