快速实现Vue双向绑定的多种常用方法

219 阅读1分钟

快速实现Vue双向绑定的多种常用方法。

1、computed

常用方法。

<script lang="ts" setup> 
import { computed } from "vue"; 
const props = defineProps({ modelValue: { type: string, default: '', }, }); 
const emit = defineEmits(["update:modelValue"]); 
const form = computed({ 
  get() { return props.modelValue; }, 
  set(newValue) { emit("update:modelValue", newValue); }, 
}); 
</script>

2、@vueuse/core

项目需集成@vueuse/core依赖,且需要对多个属性同时进行监听。

<script lang="ts" setup> 
import { useVModel } from '@vueuse/core';
const props = defineProps<{ modelValue: string }>();
const emit = defineEmits(['update:modelValue']);
const data = useVModel(props, 'modelValue', emit);
</script>

3、vue3.3+ defineModel

项目需集成vue3.3及以上版本,宏defineModel

<script lang="ts" setup> 
const count = defineModel<number>(0);
</script>