Home > front end >  Passing props to deactivated component in Vue
Passing props to deactivated component in Vue

Time:01-09

I've implemented the Tab feature using "keep-alive", like below, I want to pass "items2" data to the component when the selected currentTabComponent is 'Old', how do i make this work? is there any workaround?

<template>

   <div>
      <button @click="currentTabComponent = 'New'"> New </button>
      <button @click="currentTabComponent = 'Old'"> Old </button>
   </div>

  <keep-alive>
    <component :is="currentTabComponent" :items="currentTabComponent === 'New' ? items : items2"></component>
  </keep-alive>

</template>

In the logic, i have,

 <script>

  export default {
   data() {
     return {
        currentTabComponent: "New",
        items:['one','two','three'],
        items2:['five','six','seven']
       }
     }
  }
  
 </script>

CodePudding user response:

Even if you use keep-alive props will be passed in the usual way, dynamic or not. So if there is a change in props it should reflect in the subcomponent. keep-alive specifically helps in preserving state changes when the component is not used, and not resetting the state when the component is shown again. But in both cases, props will work fine.

Check the below code:

<div id='component-data'>
  <button
    v-for="tab in tabs"
    v-bind:key="tab"
    v-on:click="currentTab = tab">
    {{ tab }}
  </button>

  <keep-alive>
    <component v-bind:is="currentTab" 
      :items="currentTab == 'Bags' ? items[0] : items[1]"
      ></component>
  </keep-alive>
</div>

<script>
  Vue.component('Bags', {
    props: ['items'],
    template: "<div>Showing {{ items }} items in bags.</div>"
  });
  Vue.component('Shirts', {
    props: ['items'],
    template: "<div>Showing {{ items }} items in shirts.</div>"
  });

  new Vue({
    el: "#component-data",
    data: {
      tabs: ['Bags', 'Shirts'],
      currentTab: 'Bags',
      items: [100, 200]
    }
  });
</script>

You should make sure that the sub-components 'New' and 'Old' have declared the items props in their component definition. Also I hope 'New' and 'Old' are the registered names of the components you are using for tabs.

  •  Tags:  
  • Related