CodeX
1141
6
Vue

Vue components with different templates

Posted 3 years ago by CodeX

Hi,

I have 2 lists on my web page, both lists have different templates, but they both have the same behaviors (such as: loading list items, count the items etc).

Here is what my web page basically looks like:

<template id="list1-template">
   <div v-for="item in items">
        <h3>{{ item.name }}</h3>
        <p>some contents for list1</p>
   </div>
</div>

<template id="list2-template">
   <div v-for="item in items">
        <h3>{{ item.name }}</h3>
        <p>this part looks different than list1</p>
        <p>let's say I have this additional html here</p>
        <ul><li>or anything else</li></ul>
   </div>
</div>

<div id="app">
    <list1></list1>

   <list2></list2>

   <div id="summary">
        {{ list1.countItems }} - {{ list2.countItems}}
  </div>
</div>

So I think I need a component for the list but I'm still confused how to write things all together. The code below just to show what I want to achieve, it doesn't work as expected, there is no error but Vue doesn't load the items either when I check it on Vue devtools.

var listing = Vue.extend({
   data: function() {
       items: [],
       countItems: 0
   },

   ready: function() {
        this.loadItems(); 

       this.countItems();
   },

   methods: {
      loadItems: function() {
         // load items from server
      },

      countItems: function() {
          // count loaded items
       } 
   }
});

var list1 = new listing({   
   template: '#list1-template'
});

var list2 = new listing({
   template: '#list2-template'
});

Vue.component('list1',  list1);
Vue.component('list2', list2);

var app = new Vue({
   el: "#app"
});

Am I going to right direction here or is there any other way to do it? Any help would be much appreciated, thanks!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.