vue ref实现
Vue 中使用 ref 实现
在 Vue 中,ref 是一种用于获取 DOM 元素或组件实例引用的方法。它可以在模板中直接使用,也可以在组合式 API 中使用。
在模板中使用 ref
在模板中,可以通过 ref 属性标记一个 DOM 元素或子组件,随后在组件实例中通过 this.$refs 访问。
<template>
<div>
<input ref="inputRef" type="text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.inputRef.focus();
}
}
};
</script>
在组合式 API 中使用 ref
在 Vue 3 的组合式 API 中,ref 不仅可以用于模板引用,还可以用于创建响应式数据。

<template>
<div>
<input ref="inputRef" type="text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const inputRef = ref(null);
onMounted(() => {
console.log(inputRef.value); // 获取 DOM 元素
});
const focusInput = () => {
inputRef.value.focus();
};
return {
inputRef,
focusInput
};
}
};
</script>
使用 ref 创建响应式数据
ref 还可以用于创建响应式的基本类型数据(如字符串、数字等)。
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
};
</script>
ref 与 reactive 的区别
ref用于包装基本类型数据(如数字、字符串),通过.value访问。reactive用于包装对象或数组,可以直接访问属性。
import { ref, reactive } from 'vue';
const count = ref(0); // 访问 count.value
const state = reactive({ count: 0 }); // 直接访问 state.count
在子组件中使用 ref
通过 ref 可以获取子组件的实例,调用其方法或访问其数据。

<template>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">Call Child Method</button>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
setup() {
const childRef = ref(null);
const callChildMethod = () => {
childRef.value.someMethod();
};
return {
childRef,
callChildMethod
};
}
};
</script>
动态 ref
可以通过动态绑定 ref 来灵活地引用多个元素。
<template>
<div v-for="item in items" :key="item.id" :ref="setItemRef">
{{ item.text }}
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const items = ref([{ id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }]);
const itemRefs = ref([]);
const setItemRef = (el) => {
if (el) {
itemRefs.value.push(el);
}
};
onMounted(() => {
console.log(itemRefs.value); // 所有动态引用的 DOM 元素
});
return {
items,
setItemRef
};
}
};
</script>
总结
ref 在 Vue 中有多种用途:
- 获取 DOM 元素或组件实例。
- 创建响应式数据(基本类型)。
- 动态绑定多个引用。
通过合理使用 ref,可以更灵活地操作 DOM 或组件实例。






