Vue.js Dynamic Components ve Keep-Alive

Vue.js component (bileşen) kullanımına değindiğim yazı içerisinde, bir örnekte is kullanımı yer almaktaydı.

AA

Bu yazıda, öncelikle kısaca is kullanımına, ardından ise keep-alive ile bir component’in nasıl canlı tutulacağına değineceğim.

Vue Dynamic Components

Component kullanımında, genellikle name tanımını tag olarak çağırmaktaydık. Ancak, alternatif bir kullanım olarak component tag’ini is attribute ile yine component name’i belirterek işlemler yapabilmekteyiz. Örnek olarak, person adında bir component oluşturalım:

Vue.component('person', {
  template: `
  <div>
    <p>Edgar Allan Poe</p>
    <p>Born: January 19, 1809</p>
    <p>Died‎: ‎October 7, 1849</p>
  </div>`
});

Oluşturduğumuz component’i çağırmak istediğimizde <person></person> etiketlerini yazarız, değil mi? Is kullanımında aynı işlemi şu şekilde de yapabilmekteyiz:

<component is="person"></component>

Yukarıdaki kullanım sayesinde dinamik bir şekilde component’ler arasında geçiş yapabilmekteyiz1 2. Elbette bu geçişlerde ihtiyacımız olan dinamik yapısı bize v-bind direktifi sağlamakta.

<component v-bind:is="currentTabComponent"></component>

Yukarıdaki etikette currentTabComponent değiştikçe component içeriği de değişecektir. Elbette bu işlem sadece oluşturulan component adıyla sınırlı değil. Aynı kullanımı component option object için de yapabilmekteyiz. Aşağıda bahsi geçen bu 2 duruma dair örnekler paylaşıyorum.

Her iki örnekte de Bulma CSS framework tab yapısını kullanacağım.

<section id="app" class="section">
  <div class="container">
    <div class="tabs is-toggle is-fullwidth">
      <ul>
        <li v-for="tab in tabs" v-bind:key="tab" v-bind:class="{ 'is-active' : currentTab === tab }"
            v-on:click="currentTab = tab"><a>{{ tab }}</a></li>
      </ul>
    </div>

    <div id="tab-content">
      <keep-alive>
        <component v-bind:is="currentTabComponent" class="tab"></component>
      </keep-alive>
    </div>

  </div>
</section>

tabs içeriğini v-for direktifi ile edinip, v-on ile currentTab‘a aktardık. Component isimlerimiz tab-* şeklinde olduğu için - sonrasındaki tanımlamalarda component’ler arasında geçiş yapabilir hale geldik.

// Vue v2.x
Vue.component('tab-posts', {
  data() {
    return {
      posts: [{
        id: 1,
        title: 'Cat Ipsum',
        content: `<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats.Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs.My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around </p>`
      }, {
        id: 2,
        title: 'Hipster Ipsum',
        content: `<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabbychic, street art knausgaard trust fund shaman scenester live - edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR & B hoodie plaid venmo.Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8 - bit chartreuse.Trust fund food truck drinking vinegar gochujang.</p>`
      }, {
        id: 3,
        title: 'Cupcake Ipsum',
        content: `<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake.Liquorice candy macaroon toffee cookie marzipan. </p>`
      }],
      selectedPost: 0
    }
  },
  template: `
  <div>
    <div class="tabs">
      <ul class="tabContent">
        <li v-for="(post, index) in posts" :data-content="index + 1" v-bind:key="post.id" v-bind:class="{ 'is-active': selectedPost === index }" v-on:click="changeTabs(index)"><a>{{ post.title }}</a></li>
      </ul>
    </div>
    <div class="notification" v-html="this.posts[selectedPost].content"></div>
  </div>`,
  methods: {
    changeTabs(val){
      this.selectedPost = val
    }
  }
});

Vue.component('tab-archive', {
  template: `
  <div>
    <div class="tabs">
      <ul class="tabContent">
        <li><a>...</a></li>
      </ul>
    </div>
    <div class="notification">Archive component</div>
  </div>`
});

var app = new Vue({
  el: '#app',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
});

// Vue v3.x
const app = Vue.createApp({
  data() {
    return {
      currentTab: 'Posts',
      tabs: ['Posts', 'Archive']
    }
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
}).component('tab-posts', {
  data() {
    return {
      posts: [{
        id: 1,
        title: 'Cat Ipsum',
        content: `<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats.Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs.My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around </p>`
      }, {
        id: 2,
        title: 'Hipster Ipsum',
        content: `<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabbychic, street art knausgaard trust fund shaman scenester live - edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR & B hoodie plaid venmo.Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8 - bit chartreuse.Trust fund food truck drinking vinegar gochujang.</p>`
      }, {
        id: 3,
        title: 'Cupcake Ipsum',
        content: `<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake.Liquorice candy macaroon toffee cookie marzipan. </p>`
      }],
      selectedPost: 0
    }
  },
  template: `
  <div>
    <div class="tabs">
      <ul class="tabContent">
        <li v-for="(post, index) in posts" :data-content="index + 1" v-bind:key="post.id" v-bind:class="{ 'is-active': selectedPost === index }" v-on:click="changeTabs(index)"><a>{{ post.title }}</a></li>
      </ul>
    </div>
    <div class="notification" v-html="this.posts[selectedPost].content"></div>
  </div>`,
  methods: {
    changeTabs(val){
      this.selectedPost = val
    }
  }
}).component('tab-archive', {
  template: `
  <div>
    <div class="tabs">
      <ul class="tabContent">
        <li><a>...</a></li>
      </ul>
    </div>
    <div class="notification">Archive component</div>
  </div>`
}).mount('#app');

Elbette yukarıdaki örneğin üzerinden geçilebilir ve daha yalın ve fonksiyonel hale getirilebilir. Yukarıdaki örneğe temel olan ve Vue.js tarafından paylaşılan bir kullanıma buradan ulaşabilirsiniz. Her durumda da önemli olan currentTabComponent ile tab adının değiştirilebiliyor oluşu.

computed: {
  currentTabComponent: function () {
    return 'tab-' + this.currentTab.toLowerCase()
  }
}

Şimdi, bir diğer örnekte de component option object kullanalım. Yine, Vue.js tarafından paylaşılan alternatif için burayı tıklayabilirsiniz. Ben, yukarıda paylaştığım Bulma üzerinden oluşturulan örnek üzerinden ilerleyeceğim.

  <section id="app" class="section">
    <div class="container">
      <div class="tabs is-toggle is-fullwidth">
        <ul>
          <li v-for="tab in tabs" v-bind:key="tab.name" v-bind:class="{ 'is-active' : currentTab === tab }"
            v-on:click="currentTab = tab"><a>{{ tab.name }}</a></li>
        </ul>
      </div>

      <div id="tab-content">
        <keep-alive>
          <component v-bind:is="currentTab.component" class="tab" v-on:changetabs="activetab"></component>
        </keep-alive>
      </div>

    </div>
  </section>

Vue instance ise şu şekilde olsun:

var tabs = [{
  name: 'Posts',
  component: {
    template: `
    <div>
      <div class="tabs">
        <ul class="tabContent">
          <li v-for="(post, index) in this.$root.posts" :data-content="index + 1" v-bind:key="post.id" v-bind:class="{ 'is-active': $root.selectedPost + 1 === post.id }" v-on:click="$emit('changetabs', index)"><a>{{ post.title }}</a></li>
        </ul>
      </div>
      <div class="notification" v-html="this.$root.posts[this.$root.selectedPost].content"></div>
    </div>`
  }
}, {
  name: 'Archive',
  component: {
    template: `
    <div>
      <div class="tabs">
        <ul class="tabContent">
          <li><a>...</a></li>
        </ul>
      </div>
      <div class="notification">Archive component</div>
    </div>`
  }
}];

// Vue v2.x
var app = new Vue({
  el: '#app',
  data: {
    currentTab: tabs[0],
    tabs: tabs,
    selectedPost: 0,
    posts: [{
      id: 1,
      title: 'Cat Ipsum',
      content: `<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats.Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs.My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around </p>`
    }, {
      id: 2,
      title: 'Hipster Ipsum',
      content: `<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabbychic, street art knausgaard trust fund shaman scenester live - edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR & B hoodie plaid venmo.Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8 - bit chartreuse.Trust fund food truck drinking vinegar gochujang.</p>`
    }, {
      id: 3,
      title: 'Cupcake Ipsum',
      content: `<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake.Liquorice candy macaroon toffee cookie marzipan. </p>`
    }]
  },
  methods: {
    activetab(val){
      this.selectedPost = val;
    }
  }
});

// Vue v3.x
// Vue received a Component which was made a reactive object.
// This can lead to unnecessary performance overhead, and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`.
const app = Vue.createApp({
  data() {
    return {
      currentTab: tabs[0],
      tabs: tabs,
      selectedPost: 0,
      posts: [{
        id: 1,
        title: 'Cat Ipsum',
        content: `<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats.Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs.My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around </p>`
      }, {
        id: 2,
        title: 'Hipster Ipsum',
        content: `<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabbychic, street art knausgaard trust fund shaman scenester live - edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR & B hoodie plaid venmo.Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8 - bit chartreuse.Trust fund food truck drinking vinegar gochujang.</p>`
      }, {
        id: 3,
        title: 'Cupcake Ipsum',
        content: `<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake.Liquorice candy macaroon toffee cookie marzipan. </p>`
      }]
    }
  },
  methods: {
    activetab(val){
      this.selectedPost = val;
    }
  }
}).mount('#app');

Görüldüğü üzere, tabs variable içeriğinde tanımlanan name karşılıkları üzerinden component’imizi is attr aracılığıyla kullanabilmekteyiz. Peki, dikkatinizi çeken başka bir husus oldu mu? Mesela, keep-alive etiketleri?

Vue Component Keep-Alive

Evet, bir önceki başlıkta, dinamik bir şekilde component’ler arasında nasıl geçiş yapabileceğimize bakmıştık. Ancak, component’ler arasında bu geçişleri yaparken bazı durumları korumak veya performans nedeniyle component içeriğinin yeniden oluşturulmasını önlemek isteyebiliriz3 4. Yukarıdaki örneklerde, tab’ler arasında geçişler yaptığımızda son tıkladığımız tab’in aktif kalmasının nedeni tam olarak bu; keep-alive. Aksi durumda, her component geçişinde vue yeni bir currentTabComponent instance’i oluşturacaktır. İşte, bu gibi durumlarda, keep-alive ile son değişiklikleri tutabilmekteyiz.

<div id="tab-content">
  <keep-alive>
    <component v-bind:is="currentTab.component" class="tab" v-on:changetabs="activetab"></component>
  </keep-alive>
</div>

Örneklerde yer alan <keep-alive>...</keep-alive> etiketlerini kaldırarak tekrar tab’ler arasında geçiş yaptığınızda, yapılan geçişlerin korunmadığını görebilirsiniz. Keep-alive‘ın yetenekleri elbette bu kadar değil ve include, exclude, max gibi prop’larla daha kapsamlı özellikler sunabilmekte. Ancak, bu kullanımlar bir başka yazının konusu. Şimdilik Vue.js API > keep-alive sayfasını5 6 iliştirerek yazıyı sonlandırıyorum.