需求: 做一个问卷调查的页面,为了可以重复使用需要动态根据后台的数据动态判断当前位置该使用单行文本输入、多行文本输入、复选框、还是单选框,页面基于vue 3.0写的。后台的数据结构大概是这样的(模拟数据)
listData: [{
type: 'text',
label: '姓名',
value: ''
}, {
type: 'text',
label: '年龄',
value: ''
}, {
type: 'checkbox',
label: '兴趣爱好',
data: ["上网", "旅游", "篮球", "跑步"],
value: []
}, {
type: 'radio',
label: '性别',
data: ["男", "女"],
value: ''
}, {
type: 'textarea',
label: '备注1',
value: ''
}, {
type: 'textarea',
label: '备注1',
value: ''
}]
}
其中的value就是需要的数据,根据type的类型进行判断;要根据数据中的type来判断使用的类型 页面代码
<div id="app">
<div class="checkbox" v-for="(item,index) in listData" :key="index">
{{item.label}}:
<template v-if="item.type == 'text'">
<input v-model="listData[index].value" />
</template>
<template v-if="item.type == 'checkbox'">
<label v-for="(ck,index2) in item.data" :for="ck">{{ck}}<input :value="ck" v-model="listData[index].value"
type="checkbox" /></label>
</template>
<template v-if="item.type == 'radio'">
<label v-for="(rd,index2) in item.data" :for="rd">{{rd}}<input :value="rd" :value="rd"
v-model="listData[index].value" name="sex" type="radio" /></label>
</template>
<template v-if="item.type == 'textarea'">
<textarea v-model="listData[index].value" name="" id="" cols="30" rows="10"></textarea>
</template>
</div>
<button @click="submit">提交</button>
</div>
效果如下
可以看出页面输出是没问题,跟预想的一样。当点击提交的时候,所输入和选中的值就展示在
listData中的vlaue里面
全部代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>基于问卷调查需求vue给v-model动态绑定变量</title>
</head>
<body>
<div id="app">
<div class="checkbox" v-for="(item,index) in listData" :key="index">
{{item.label}}:
<template v-if="item.type == 'text'">
<input v-model="listData[index].value" />
</template>
<template v-if="item.type == 'checkbox'">
<label v-for="(ck,index2) in item.data" :for="ck">{{ck}}<input :value="ck" v-model="listData[index].value"
type="checkbox" /></label>
</template>
<template v-if="item.type == 'radio'">
<label v-for="(rd,index2) in item.data" :for="rd">{{rd}}<input :value="rd" :value="rd"
v-model="listData[index].value" name="sex" type="radio" /></label>
</template>
<template v-if="item.type == 'textarea'">
<textarea v-model="listData[index].value" name="" id="" cols="30" rows="10"></textarea>
</template>
</div>
<button @click="submit">提交</button>
</div>
<script src="https://cdn.qianduan.cn/vue/3.0.0/vue.global.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
listData: [{
type: 'text',
label: '姓名',
value: ''
}, {
type: 'text',
label: '年龄',
value: ''
}, {
type: 'checkbox',
label: '兴趣爱好',
data: ["上网", "旅游", "篮球", "跑步"],
value: []
}, {
type: 'radio',
label: '性别',
data: ["男", "女"],
value: ''
}, {
type: 'textarea',
label: '备注1',
value: ''
}, {
type: 'textarea',
label: '备注1',
value: ''
}]
}
},
methods: {
submit() {
console.log(this.listData)
}
}
})
const vm = app.mount("#app");
</script>
</body>
</html>