萌新小白请教,不太明白为什么使用 ref 数据可以双向绑定,使用 reactive 数据无法双向绑定?是我用法不对吗?
到底什么时候应该使用 ref 什么时候应该使用 reactive 呢?
直接展示代码:
App.vue
<script setup> import { ref, reactive } from 'vue' import Comp from './Comp.vue' // const styleCOnfig= ref({ // fontSize: 16 // }) const styleCOnfig= reactive({ fontSize: 16 }) </script> <template> <p :style="{ fontSize: styleConfig.fontSize + 'px'}">我是字体</p> <Comp v-model="styleConfig" /> </template> Comp.vue
<script setup lang="ts"> import { reactive, watch } from 'vue' interface StyleConfig { fontSize: number } interface Props { modelValue: StyleConfig } const props = defineProps<Props>() interface Emits { (e: 'update:modelValue', value: StyleConfig): void } const emit = defineEmits<Emits>() const localCOnfig= reactive<StyleConfig>({ ...props.modelValue }) watch(localConfig, (newConfig) => { emit('update:modelValue', { ...newConfig }) }, { deep: true }) </script> <template> <div> <label>字体大小</label> <input v-model="localConfig.fontSize" /> </div> </template> 
