vue3和vue2获取元素的不同:vue2是通过 this.$refs api获取dom节点的 ; vue3是 直接使用同名的 ref 响应式数据来获取的;

1,常规使用

注意: 节点上的 ref=“input” 需要和 const input = ref(null)相对应 才能获取到此dom节点

<script setup>
import { reactive, ref, createApp, onMounted } from "vue";

let state = reactive({ text: "信息按钮" });
// 同名的 input来进行获取节点
const input = ref(null);
onMounted(() => {
  if (input.value) {
    input.value.focus();
  }
});
</script>

<template>
  <div class="ref">
    <h3>ref使用:</h3>
    <input type="text" ref="input" /> //  ref="input" 需要和 const input = ref(null); 相对应
  </div>
</template>

<style scoped></style>

2,v-for中的ref获取
有时我们需要 获取循环中的dom节点 并根据状态进行一些操作;
以下案例是:循环list后,并拿到所循环的dom节点 并把钟离的字体颜色变为蓝色:

<script setup>
import { reactive, ref, createApp, onMounted } from "vue";
const refList = ref([]); // 存放dom节点的数组的 获取到的dom节点都在这里

const list = ref([{ name: "钟离" }, { name: "行秋" }, { name: "香菱" }]); // 普通的响应式数据
onMounted(() => {

  // ref列表使用
  if (refList.value) {
    console.log("refList:", refList.value);
   
    // 我拿到了每个循环出来的dom节点 那么我就可以做一些操作了 比如 改变名为钟离的字体颜色
    refList.value.forEach(item=>{
      if(item.innerText === '钟离'){
        item.style.color = "blue"  //钟离的字体颜色改变成功
      }
    })

  }
});
</script>

<template>
  <div class="ref">
    <h4>ref列表循环</h4>
    <ul>
      <li v-for="({ name }, index) in list" ref="refList" :key="index">
        {{ name }}
      </li>
    </ul>
  </div>
</template>

<style scoped></style>

结果如下:
在这里插入图片描述
3,组件上的,使用 ref

<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'

const child = ref(null)

onMounted(() => {
  // child.value 是 <Child /> 组件的实例
})
</script>

<template>
  <Child ref="child" />
</template>

如果一个子组件使用的是选项式 API 或没有使用 <script setup>,这意味着父组件对子组件的每一个属性和方法都有完全的访问权;

如果使用了 <script setup> 的组件是默认私有的:一个父组件无法访问到一个使用了 <script setup> 的子组件中的任何东西,除非子组件在其中通过 defineExpose 宏显式暴露:如下:

<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
  a,
  b
})
</script>

当父组件通过模板引用获取到了该组件的实例时,得到的实例类型为 { a: number, b: number } (ref 都会自动解包,和一般的实例一样)。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐