简体   繁体   English

将Vue.js混合到现有的SSR网站中?

[英]Mixing Vue.js into existing SSR website?

Is it possible/viable to use Vue to create components that get instantiated onto custom tags rendered by eg a PHP application? 使用Vue创建可以实例化到由PHP应用程序呈现的自定义标记的组件是否可行/可行? 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. 如果我将Vue实例挂载到页面根元素上,它“有效”,但是 - 据我所知 - 在这种情况下,Vue使用整个页面作为模板。 And I imagine this could be a performance issue and cause trouble if other javascript code messes with the DOM. 我想这可能是一个性能问题,并且如果其他javascript代码与DOM混淆会导致麻烦。

The goal is to progressively replace legacy jQuery code. 目标是逐步替换传统的jQuery代码。 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. 编辑2:一些小提琴来说明问题。

A working solution based on riot.js: https://jsfiddle.net/36xju9sh/ 基于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/ 使用Vue.js的两种方法: https ://jsfiddle.net/89ejjjsy/1/

HTML: 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: 使用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',
});

You do not have to use whole page as Vue instance scope. 您不必将整个页面用作Vue实例范围。 It is more than ok to for example, use #comments-container as scope for comments component which will be nested somewhere on your page. 例如,使用#comments-container作为注释组件的范围,它将嵌套在页面的某个位置。

You can have multiple VueJS instances on one page. 您可以在一个页面上拥有多个VueJS实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM