vue3.3.x setup 新实验性特性 defineModel 定义多个属性
由于有些业务组件需要定义多个响应式props
,类似这种(比较懒,没上ts),在vue3.3.x以前,如果不用三方库,代码会变得很繁琐
<script setup>
const props = defineProps({
modelValue: {
type: Object,
default: () => ({})
},
fields: {
type: Object,
default: () => ({})
},
list: {
type: Array,
default: () => []
},
loading: Boolean
})
const emit = defineEmits('update:modelValue', 'update:fields', 'update:list', 'update:loading')
const onUpdateModelValue = (value) => {
emit('update:modelValue', value)
}
const onUpdateLoading = (value) => {
emit('update:loading', value)
}
// ...
</script>
正好vue3.3.x更新了新apiuseModel
(原本使用的vueuse的useVModel
),于是做出如下调整
<script setup>
import { useModel } from 'vue'
const props = defineProps({
modelValue: {
type: Object,
default: () => ({})
},
fields: {
type: Object,
default: () => ({})
},
list: {
type: Array,
default: () => []
},
loading: Boolean
})
const emit = defineEmits('update:modelValue', 'update:fields', 'update:list', 'update:loading')
const modelValue = useModel(props, 'modelValue')
const fields = useModel(props, 'fields')
const list = useModel(props, 'list')
const loading = useModel(props, 'loading')
</script>
虽然用了vue3.3.x的新特性useModel
,但是还是需要定义emit
,所以代码还是觉得有点多,然后想到了跟useModel
一起发布的defineModel
,但是百度了一圈,都只有ts版本的defineModel
,而且大部分是单个响应式props,多个属性的响应式配置完全摸不着头脑,于是只能去找找源码,还好源码注释很详细,被我找到了解决方案,具体实现如下
<script setup>
import { defineModel } from 'vue' // 好像可以引入
const modelValue = defineModel({ type: Object, default: () => ({}) })
const fields = defineModel('fields', { type: Object, default: () => ({}) })
const list = defineModel('list', { type: Array, default: () => [] })
const loading = defineModel('loading', { type: Boolean })
</script>