DatsunBing
DatsunBing

Reputation: 9076

Correct way to use Vue component mutiple times in one page

I am trying to create a simple 24 hour time input that I can use across multiple browsers.

In the past I have used Vue to create components which are used once on a page, and I attach them to an id as follows:

<script>
    $(function () {
        new Vue({
            el: "#my-time-element"
        });
    });
</script>

But what happens when I want to use it multiple times in one page? I tried attaching it using a class definition (attach to .my-element) but it only renders for the first matching element. (The component is registered globally.)

Perhaps I am supposed to wrap the page in a single Vue component, then embed my time component in its template? Perhaps I need to make a jQuery collection of all .my-element elements, then cycle through and instantiate Vue for each one? What is the correct way to approach this?

Upvotes: 4

Views: 3004

Answers (1)

ghybs
ghybs

Reputation: 53370

Perhaps I am supposed to wrap the page in a single Vue component, then embed my time component in its template?

That is definitely the easiest way to do it.

You do not have to change so many things compared to your regular HTML page: simply make sure to provide an ID to one of your root container, then use your Custom Component tag anywhere within and as many times you like.

You just need to prepare Vue by globally declaring your custom component first, with Vue.component:

Vue.component('my-component', {
  template: '#my-component',
});

new Vue({
  el: '#app',
});
<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <h1>Hello World</h1>
  <my-component>Component instance 1</my-component>
  <my-component>Component instance 2</my-component>
</div>

<template id="my-component">
  <div style="border: 1px solid black">
    <h2>My component</h2>
    <slot></slot>
  </div>
</template>

Perhaps I need to make a jQuery collection of all .my-element elements, then cycle through and instantiate Vue for each one?

That is also a possible solution, but probably defeats the Vue spirit…

Upvotes: 4

Related Questions