SoFunction
Updated on 2025-04-04

Three ways to refresh the subcomponent in vue to reload the subcomponent

  • In the parent component, new data is passed to the child component by modifying the value of props, thereby triggering the update of the child component.
  • In the parent component:
    <template>
      <child-component :dataProp="parentData" />
    </template>
    
    <script>
    export default {
      data() {
        return {
          parentData: 'Initial data'
        };
      },
      methods: {
        updateChildComponent() {
           = 'New data';
        }
      }
    };
    </script>
    
  • In the child component:

    <template>
      <div>{{ dataProp }}</div>
    </template>
    
    <script>
    export default {
      props: ['dataProp']
    };
    </script>
    

    2. Refer to the subcomponent using $refs:

  • Use in parent componentrefCreate a reference for a child component, and then directly call the child component's methods or access its data by reference.
  • In the parent component:
    &lt;template&gt;
      &lt;child-component ref="childRef" /&gt;
    &lt;/template&gt;
    
    &lt;script&gt;
    export default {
      methods: {
        updateChildComponent() {
          // Call the method of the child component or access the data through $refs      this.$();
        }
      }
    };
    &lt;/script&gt;
    
  • In the child component:

    &lt;template&gt;
      &lt;!-- Subcomponent content --&gt;
    &lt;/template&gt;
    
    &lt;script&gt;
    export default {
      methods: {
        someMethod() {
          // Here you can perform the operation of refreshing the subcomponent    }
      }
    };
    &lt;/script&gt;
    

    3. Add key value to child components

  • After the key value changes, the component will be automatically re-rendered. The key in vue is mainly used to efficiently update the dom. It can also be used to force the element/component to be replaced instead of reusing it. The completed triggers the component's life cycle hook and triggers the transition.

  • Parent component:

    &lt;template&gt;
       &lt;el-button @click="click"&gt;Refresh subcomponents&lt;/el-button&gt;
      &lt;child-component :key="datekey" /&gt;
    &lt;/template&gt;
     
    &lt;script&gt;
       export default{
           data(){
              return {
                    datekey:()
                }
           },
        methods:{
            click(){
                //If the datekey is updated here, the component will be refreshed             = ()
            }
        }
    }
    &lt;/script&gt;