Search code examples
javascriptvue.jsdynamicvue-componentreactive

Vue3 Dynamic Component Return Props


Messing around with Vue3's Dynamic Component <component>, and I have this current setup:

Component 1:

<template>
  <div>
    <h1> Input name: </h2>
    <Input :model="props.name" />
    <p> {{props.example}} </p>
  </div>
</template>
<script>
export default{
  props:["props"]
}
</script>

Main File

<template>
  <div>
    <component :is='active.page' :props='active.props' />
  </div>
</template>
<script>
import UserName from 'components/UserName.vue'
export default{
  components: { UserName }
  setup() {
    const active = { page: 'UserName', props: { name: null, example: 'Dave' } }

    return {active}
  }
}  

Eventually, there will be multiple pages that the user can navigate through using a <Button /> of sorts; the question is: Is it possible to return the prop name back to the Main File after it has been modified inside Component 1?

The reason is that it needs to be passed to the next pages within <component> for display when the user presses next

Thanks for the assistance


Solution

  • You can use emit to pass the name back to the Main File and do not modify the props directly, declare another variable to store it and modify this variable.

    // Component 1
    <template>
      <div>
        <h1> Input name: </h1>
        <Input v-model="name" />
        <p> {{props.example}} </p>
      </div>
    </template>
    <script>
    import { defineEmits } from 'vue'
    export default {
      props:["props"],
      emits: ['name-updated'],
      data() {
        return {
          name: this.props.name
        }
      },
      watch: {
        name() {
          this.$emit('name-updated', this.name)
        }
      }
    }
    </script>
    
    // Main File
    <template>
      <div>
        <component :is='active.page' :props='active.props' @name-updated="updateName" />
      </div>
    </template>
    <script>
    import UserName from 'components/UserName.vue'
    export default{
      components: { UserName },
      setup() {
        const active = { page: 'UserName', props: { name: null, example: 'Dave' } }
        const updateName = (newName) => {
          active.props.name = newName
        }
        return {active, updateName}
      }
    }  
    </script>