3

Is it possible/viable to use Vue to create components that get instantiated onto custom tags rendered by e.g. a PHP application? Some kind of "custom elements light"?

It "works" if I mount the Vue instance onto the page root element, but - as far as I understand - Vue uses the whole page as a template in this case. And I imagine this could be a performance issue and cause trouble if other javascript code messes with the DOM.

The goal is to progressively replace legacy jQuery code. Is there an common approach for this problem?

Edit: Nesting these components is also a requirement. A simple example would be nested collapsibles.

Edit 2: Some fiddles to illustrate the problem.

A working solution based on riot.js: https://jsfiddle.net/36xju9sh/

<div id="page">
  <!-- This is supposed to show "This is a test." twice. -->
  <test>
    <test></test>
  </test>
</div>
<script type="riot/tag">
  <test>
    <p>This is a test.</p>
    <yield/>
  </test>
</script>
<script>riot.mount('*')</script>

Two approaches using Vue.js: https://jsfiddle.net/89ejjjsy/1/

HTML:

<div id="page">
  <!-- This is supposed to show "This is a test." twice. -->
  <test>
    <test></test>
  </test>
</div>
<script type="text/x-template" id="test-template">
  <p>This is a test.</p>
  <slot></slot>
</script>

Javascript:

Vue.config.ignoreCustomElements = ['test'];

// This won't hit the nested <test> element.
new Vue({
    el:'test',
    template: '#test-template',
});

// This does, but takes over the whole page.
Vue.component('test', {
    template: '#test-template',
});

new Vue({
  el: '#page',
});
Philipp Melab
  • 409
  • 1
  • 4
  • 14
  • `Vue` instances are independent unless they are components, so start with independent `Vue` with localized functionalities, later when done, convert them to components and use a single Vue app. – Mat J Jan 12 '17 at 04:59
  • I forgot to mention that nesting is also a requirement. Edited the question accordingly. – Philipp Melab Jan 12 '17 at 07:01
  • 1
    That's fine, you can use components within each Vue instance. Just don't share the instances between these independent items. always create their own.. [Something like this](https://jsfiddle.net/cuokx1h2/) will work right? – Mat J Jan 12 '17 at 08:05

1 Answers1

0

You do not have to use whole page as Vue instance scope. It is more than ok to for example, use #comments-container as scope for comments component which will be nested somewhere on your page.

You can have multiple VueJS instances on one page.

Marek Urbanowicz
  • 12,659
  • 16
  • 62
  • 87
  • I meant nested within each other. Not nested on the page. I've created a fiddle to illustrate the problem: https://jsfiddle.net/89ejjjsy/ – Philipp Melab Jan 12 '17 at 08:55