pass modelValue in dynamic component vue 3
- User
pass modelValue in dynamic component vue 3
- Assistant
In Vue 3, you can pass data such as
modelValueto a dynamic component using the:isattribute for component resolution. Thev-modeldirective is commonly used withmodelValuefor two-way binding. Here's a step-by-step guide on how to accomplish this:Step 1: Define the Components
First, make sure you have the components you wish to render dynamically. For example, let's consider two simple components:
vue<!-- MyComponentA.vue --> <template> <div> <input type="text" v-model="inputValue" /> </div> </template> <script setup> import { defineProps } from 'vue'; const props = defineProps({ modelValue: String }); const inputValue = ref(props.modelValue); watch(() => inputValue.value, (newValue) => { emit('update:modelValue', newValue); }); </script>vue<!-- MyComponentB.vue --> <template> <div> <p>{{ message }}</p> </div> </template> <script setup> import { defineProps } from 'vue'; const props = defineProps({ modelValue: String }); const message = computed(() => `The passed message is: ${props.modelValue}`); </script>Step 2: Use Dynamic Component in Parent
In your main parent component, you can dynamically render these components and pass the
modelValue.vue<!-- ParentComponent.vue --> <template> <div> <label for="componentSelector">Choose a component:</label> <select id="componentSelector" v-model="currentComponent"> <option value="MyComponentA">Component A</option> <option value="MyComponentB">Component B</option> </select> <component :is="currentComponent" v-model="sharedValue" /> </div> </template> <script setup> import { ref } from 'vue'; import MyComponentA from './MyComponentA.vue'; import MyComponentB from './MyComponentB.vue'; const currentComponent = ref('MyComponentA'); const sharedValue = ref('Initial Value'); </script>