模版引用_vue

模版引用-vue

效果

代码

<!-- template 模版-->
<template>
  <div ref="container" class="container">容器</div>
  <button @click="getElementHandle">获取元素</button>
  <input type="text" ref="username" placeholder="请输入用户名" />
</template>
<!-- 内容改变,用:{{模版语法}} -->
<!-- 属性改变,用v-bind:属性名="变量名" -->
<!-- 事件绑定,用v-on:事件名="方法名" -->
<!-- 事件绑定简写,用@事件名="方法名" -->
<!-- 如果没有特别需求,不要操作DOM,耗性能 -->
<script lang="ts" setup>
import { ref } from 'vue';

// 创建模板引用
const container = ref<HTMLElement | null>(null);
const username = ref<HTMLInputElement | null>(null); // 声明 username 引用

const getElementHandle = () => {
  // 访问 ref 创建的引用
  if (container.value) {
    console.log(container.value);
    // 可以访问 DOM 属性和方法
    console.log('元素内容:', container.value.textContent);
    console.log('类名:', container.value.className);
    container.value.innerHTML = '内容已改变';
    container.value.style.backgroundColor = 'lightblue'; // 改变背景颜色
    console.log('元素内容:', username.value);
    console.log('用户名:', username.value?.value); // 使用可选链操作符访问 username 引用
    if (username.value) {
      username.value.focus(); // 设置焦点
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}
</style>

posted @ 2025-05-06 20:25  guixiang  阅读(12)  评论(0)    收藏  举报