因业务需要用到低代码,v-model绑定的是随机生成的

<template>
<input type="text" v-model="form[key]">
<button @click="submit">提交</button>
</template>
<script setup>
import { ref } from "vue"
const form = ref({})
const key = ref("input-123456")
const submit = () => {
console.log(form.value)
}
</script>

Vue3根据动态字段绑定v-model的操作代码

VUE动态绑定v-model变量(ui框架iview)

需求

最近在学习vue技术,开发表格的时候,想把表格做成组件,那查询条件就需要动态生成,这就遇到一个问题,vue怎么动态给v-model变量值。

UI框架使用的是iview

页面渲染(子组件)

 <div class="ivu-card-body">
<Form ref="formInline" v-model="formInline" inline>
<Row type="flex" justify="end" align="middle">
<Col
:xs="24"
:sm="24"
:md="6"
:lg="12"
:xl="8"
class="form-item-col"
v-for="(formItem, formIndex) in formArray"
:key="formItem.id"
:value="formIndex"
>
<FormItem :label="formItem.label + ':'">
<Input
v-if="formItem.componentType == 'input'"
:type="formItem.type"
v-model="formInline[formItem.model]"
:placeholder="formItem.placeholder"
>
</Input>
</FormItem>
</Col>
<Col
:xs="24"
:sm="24"
:md="6"
:lg="12"
:xl="8"
class="form-item-col ivu-btn-right"
>
<FormItem>
<Button
type="primary"
class="ivu-seach-btn"
@click="SeachHanler"
>搜索</Button>
</FormItem>
</Col>
</Row>
</Form>
</div>

子组件js

export default {
name: "TableSearch",
props: {
formArray: {
type: [Object, Array],
default: () => {}, //这边是箭头函数
},
},
data() {
var dataInit = {
formInline: {}, //查询条件form
};
return dataInit;
},
watch: {
// 处理循环的数据
formArray() {
this.formArray.map((item) => {
if (item && item.model && item.modelValue) {
this.$set(this.formInline, item.model, item.modelValue);
}
});
},
},
methods: {
//搜索
SeachHanler() {
this.$emit("on-search", this.formInline);
}
},
mounted() {},
created() {},
};

父组件使用

  data() {
return {
formArray: [
{
componentType: "input",
type: "text",
model: "UserName",
modelValue: "用户1",
placeholder: "请输入用户名1111",
label: "用户名111",
id: "1",
},
{
componentType: "input",
type: "text",
model: "Phone",
modelValue: "11111",
placeholder: "请输入电话",
label: "电话",
id: "2",
}
]
};
},

遇到的问题以及解决

1.问题: 怎么让变量值绑定到v-model上
解决: v-model="formInline[formItem.model]"
其中formInline是在form组件上定义的一个对象

2.问题:变量值绑定上去了,怎么去让数据显示到子组件的“data”中
解决: 通过watch监听 formArray的值变化,然后使用下面的代码进行反显,不然会导致v-model绑定的变量无法修改。
this.$set(this.formInline, item.model, item.modelValue);

到此这篇关于Vue3根据动态字段绑定v-model的文章就介绍到这了,更多相关Vue3动态绑定v-model内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。