ref和reactive
- reactive 适合复杂对象
- ref 适合简单的响应式,或者DOM
1、创建对象
import { ref,reactive } from 'vue';
const count = ref(0);
count.value++;
const user = reactive({
name: 'John Doe',
address: {
street: '123 Main St',
city: 'Anytown'
}
});
2、Vue3 ref获取DOM( inputRef.value)
<template>
<div>
<input ref="inputRef" type="text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const inputRef = ref(null);
const focusInput = () => {
inputRef.value.focus();
};
onMounted(() => {
inputRef.value.focus();
});
</script>
3、Vue2 ref获取DOM( this.$refs.inputRef)
<template>
<div>
<input ref="inputRef" type="text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.inputRef.focus();
}
},
mounted() {
// 组件挂载后自动聚焦输入框
this.$refs.inputRef.focus();
}
};
</script>
4、toRef和toRefs
toRef
<template>
<div>
{{ nameRef}}
</div>
</template>
<script setup>
import { reactive, toRef } from 'vue'
const state = reactive({
name: 'Vue 3',
version: '3.0.0'
})
const nameRef = toRef(state, 'name')
</script>
<style scoped>
</style>
toRefs
<template>
<div>
{{ refs.name }} ---{{ refs.version }}
</div>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
const state = reactive({
name: 'Vue 3',
version: '3.0.0'
})
const refs = toRefs(state)
</script>
<style scoped>
</style>