萌新小白请教,不太明白为什么使用 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>
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.