BeHFaR
BeHFaR

Reputation: 129

How to keep the changes when components get rendered again in Vuejs

I have 4 components that depending on two boolean values onePage and currentStep should be loaded one by one or all together.

   <div v-if="!onePage">
    <Component_1 v-show="currentStep === 1"  @eventHandler1="someFunc()" :prop="someData1" />
    <Component_2 v-show="currentStep === 2"  @eventHandler2="someFunc()" :prop="someData2" />
    <Component_3 v-show="currentStep === 3"  @eventHandler3="someFunc()" :prop="someData3"/>
    <Component_4 v-show="currentStep === 4"  @eventHandler4="someFunc()" :prop="someData4" />
  </div>

  <div v-else class="mt-5 pt-1">
    <Component_1  @eventHandler1="someFunc()" :prop="someData1" />
    <Component_2  @eventHandler2="someFunc()" :prop="someData2" />
    <Component_3  @eventHandler3="someFunc()" :prop="someData3"/>
    <Component_4  @eventHandler4="someFunc()" :prop="someData4" />
  </div>

The question is how to keep the changes within each one of the components when onePage gets toggled?

Cause for example Component1 won't keep the internal changes made when onePage: false, currentStep: 1 (e.g. changes of a data object) and it gets reset to the default values when it gets rendered through the v-else condition in the second Div

Upvotes: 0

Views: 561

Answers (1)

Mon
Mon

Reputation: 11

In your code, component_x in 2 blocks are different components, that means they have different internal state data, therefore toggling onePage actually toggles show/hide different components, and internal changes can't be kept. However, you can consider to put all internal state data into a prop object, then in the parent, you initialize the object and pass it to the 2 components.

EDIT: Following can be a solution as well and it uses only one instance for each component 1->4. You don't have to move internal states to prop either.

  <div class="mt-5 pt-1"> <!-- you can add class binding here if needed -->
    <Component_1 v-show="onePage || currentStep === 1" @eventHandler1="someFunc()" :prop="someData1" />
    <Component_2 v-show="onePage || currentStep === 2" @eventHandler2="someFunc()" :prop="someData2" />
    <Component_3 v-show="onePage || currentStep === 3" @eventHandler3="someFunc()" :prop="someData3"/>
    <Component_4 v-show="onePage || currentStep === 4" @eventHandler4="someFunc()" :prop="someData4" />
  </div>

Upvotes: 1

Related Questions