I want to wrap the parent component conditionally without affecting the chikd component. Please check below example of what exactly I want in vue 3
<template>
<el-col v-if="column.length> 0" :xs="column.xs" :sm="column.sm" :lg="column.lg" :xl="column.xl">
<el-form-item
:prop="formItems.prop"
:label="formItems.label"
>
<el-input
v-model="props.modelValue"
@input="$emit('update', $event)"
:placeholder="props.placeholder"
:type="props.type"
:autocomplete="props.autocomplete"
:suffix-icon="props.icon"
/>
</el-form-item>
</el-col>
</template>
Here I want to wrap <el-col>
component with specific condition. I have used the v-if but not work as I need to show the child element as it is just want to wrap parent component <el-col>
conditionally.
Working code but returning warning
[Vue warn] Set operation on key "modelValue" failed: target is readonly.
on typing
Parent component
<template>
<InputColumn
:column="{ xs: 24, sm: 12, lg: 8, xl: 6 }"
:formItems="{
label: 'Prefix',
prop: 'prefix',
rules: [
{
required: true,
message: 'Enter value',
trigger: 'change',
},
],
}"
v-model="prefix"
placeholder="Prefix"
@update="(v) => (prefix = v)"
/>
</template>
Child component
<template>
<el-col :xs="column.xs" :sm="column.sm" :lg="column.lg" :xl="column.xl">
<el-form-item
:prop="formItems.prop"
:label="formItems.label"
:rules="formItems.rules"
>
<el-input
v-model="props.modelValue"
@input="$emit('update:modelValue', $event)"
:placeholder="props.placeholder"
:type="props.type"
:autocomplete="props.autocomplete"
:suffix-icon="props.icon"
/>
</el-form-item>
</el-col>
</template>
<script setup>
defineEmits(["update:modelValue"]);
const props = defineProps({
modelValue: {
type: [String, Number],
required: true,
default: "",
},
type: {
type: String,
required: false,
default: "",
},
placeholder: {
type: String,
required: false,
default: "",
},
autocomplete: {
type: String,
required: false,
default: "off",
},
icon: {
type: String,
required: false,
default: "",
},
formItems: {
type: Object,
required: false,
},
column: {
type: Object,
required: false,
default: { xs: 24, sm: 24, lg: 8, xl: 8 },
},
});
</script>
CodePudding user response:
If you will apply a condition on the parent element, it will affect its child elements as well.
It's better to move your child elements into any component, and use it like this-
<template>
<!-- If condition true, wrap child elements inside parent -->
<el-col
v-if="column.length> 0"
:xs="column.xs"
:sm="column.sm"
:lg="column.lg"
:xl="column.xl"
>
<child-elements/>
</el-col>
<!-- Else show child elements without wrapped -->
<child-elements v-else/>
</template>