• vue3 - vue3中使用ref来获取dom节点


    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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

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

    <script setup>
    import { ref, onMounted } from 'vue'
    import Child from './Child.vue'
    
    const child = ref(null)
    
    onMounted(() => {
      // child.value 是  组件的实例
    })
    </script>
    
    <template>
      <Child ref="child" />
    </template>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    如果一个子组件使用的是选项式 API 或没有使用