Vue3组件v-model

开发过程中有时会需要给父子组件数据双向绑定。在这里记录一下,废话不多说 ,上代码

<template>
	<el-select v-model="currentValue" @change="change">
		<el-option v-for="opt in options" :key="opt.value" :label="opt.label" :value="opt.value" />
	</el-select>
</template>

<script setup lang="ts">
import { onMounted, ref, toRefs } from 'vue';
import { knowledgeDict } from '/@/api/knowledgeBase/common';
import { STATUS_CODE } from '/@/enum/global';
interface Props {
	dataCategoryId: number;
	modelValue: any; // 父组件传过来的值
}
const props = defineProps<Props>();
const emits = defineEmits(['update:modelValue']);
const { dataCategoryId } = toRefs(props);
const currentValue = ref<any>(); // 子组件中设置一个变量,否则select的v-model不生效。之所以不用modelValue,是因为在vue中父组件传过来的是一个只读的,不允许修改
const options = ref<SelectOptionType[]>();

const change = (value: any) => {
	emits('update:modelValue', value); // 通过 update:modelValue 触发父组件的事件,将修改后的值传递给父组件,在父组件中进行修改。
};

const getOptions = async () => {
	const { code, data } = await knowledgeDict({ category: dataCategoryId.value });
	if (code === STATUS_CODE.SUCCESS && data[dataCategoryId.value]) {
		options.value = data[dataCategoryId.value].map((item: { value: any; code: any }) => ({
			label: item.value,
			value: item.code,
		}));
	}
};

onMounted(() => {
	getOptions();
});
</script>

<style lang="scss" scoped></style>

在父组件中调用

<template v-for="(item, index) in label" >
    <SelectCom
        :key="index"
	    :modelValue="data[item.prop]"
	    :dataCategoryId="item.dataCategoryId"
	    @update:modelValue="(value) => (data[item.prop] = value)"
    ></SelectCom>
</template>

代码中出现的 STATUS_CODE 等是系统定义的一些常量,大家根据自己系统的代码进行修改即可。

注:vue官网中对这部分内容也做了详细介绍,除了我使用的这种方法外,还可以使用vue提供的defineModel这个便利宏来实现。

组件 v-model | Vue.js

计算机中的宏-参考文档

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值