Vue3+ts+NaiveUI自定义组件
最近接触个项目,有一部分区域有很高的相似度,所以想封装成共通。具体代码如下。
前提:有一个主页面,里面有多个相同区域(例如:
区域1=下拉列表+入力框+...+按钮。
区域2=下拉列表+入力框+...+按钮。
区域3=下拉列表+入力框+...+按钮。
需求,因为有大量相同代码,需要将【下拉列表+入力框+...+按钮。】封装成一个vue文件。
1. 定义共通组件内容
<template>
<!-- 循环绑定的模型数据 -->
<template v-for="(item, index) in model.plan" >
<div class="">固定文言</div>
<div class="">单位:{{model.unit}}</div>
<div class=" style="">
频度: {{model.frequency}}
</div>
<n-grid :cols="3">
<n-gi :span="1" class="">
<n-form-item
:key="index + '下拉列表'"
:label="'下拉列表'"
:path="`${model.checkPath}[${index}].methodSummary`"
:rule="{
required: true,
trigger: ['input', 'change']
}"
>
<n-select
v-model:value="item.methodSummary"
class=""
clearable
placeholder=""
:options="model.summaryOptions"
/>
</n-form-item>
</n-gi>
<n-gi :span="1" class="">
...略
</n-gi>
</n-grid>
</template>
</template>
<script lang="ts">
export default {
name: 'CommonInput'
}
</script>
<script lang="ts" setup>
// 接收主画面参数
const props = defineProps([
'title', // 标题
'unit', // 单位
'frequency', // 频度
'summaryOptions',//下拉列表数据
'monitoringPlan',//循环数据列表
'checkPath'//必须入力check的固定文字
])
// 定义数据模型
const model = reactive({
title: '',
unit: '',
frequency: '',
summaryOptions: [],
monitoringPlan: [
{
methodSummary: '',
methodDetail: '',
comment: ''
}
],
checkPath: ''
})
// 将接收的参数给模型赋值
const handleInit = () => {
model.title = props.title
model.unit = props.unit
model.frequency = props.frequency
model.summaryOptions = props.summaryOptions
model.monitoringPlan = props.monitoringPlan
model.checkPath = props.checkPath
}
// 调用初期化方法
handleInit()
</script>
2. 主页面嵌入自定义的共通组件
<template>
//第一次引用
<CommonInput
:title="`标题1`"
:unit="`/m3`"
:frequency="`小标题1`"
:summaryOptions="select1"
:plan="planModel.plan1"
:checkPath="`plan1`"
></CommonInput>
//第二次引用
<CommonInput
:title="`标题2`"
:unit="`/m2`"
:frequency="`小标题2`"
:summaryOptions="select2"
:plan="planModel.plan2"
:checkPath="`plan2`"
></CommonInput>
</template>
<script lang="ts" setup>
// 引入自定义组件
import CommonInput from '@/views/common/index.vue'
// 定义模型数据
const planModel = reactive({
plan1: [
{
methodSummary: '',
methodDetail: '',
comment: ''
}
],
plan2: [
{
methodSummary: '',
methodDetail: '',
comment: ''
}
]
})
// 定义下拉列表固定值
const select1: any = reactive([
{ value: '001', label: '' },
{ value: '002', label: '值1' }
])
const select2: any = reactive([
{ value: '101', label: '' },
{ value: '102', label: '内容1' },
{ value: '103', label: '内容2' }
])
// 下记略
</script>
注意事项:无须指定返回值,主画面planModel可以自动取到,小画面更改的数据。