VueJS 未在 jquery ajax 加载时呈现组件

VueJS not rendering component on jquery ajax load

我有两个 HTML 文件,每当我单击 link-a 时,它都会触发

$( "#content" ).load( "nav-a.html" );

我的base.html文件

<div id="content">
</div>

我的导航-a.html

<component-a> </component-a>

我的问题是 component-a 没有渲染,是否可以在 jquery ajax 加载?我在 .load 回调上尝试了 vm.compile() 和 vm.$forceUpdate() 但没有任何反应。

不,有几个原因:

你可能不应该让另一个脚本修改由 VueJS 控制的 DOM 元素。它很可能会在最后破坏事物。要执行 http 请求,您可以使用 Vue-resource。当然它不会更新 DOM (您应该将其映射到模板); MVVM 框架的整体理念是拥有一个数据模型和您的视图。

但即使在这种情况下,您也不能使用原始 html 注入直接渲染组件,正如 v-html 指令的文档中所说:

The contents are inserted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.

来源:https://vuejs.org/v2/guide/syntax.html#Raw-HTML

所以您可能想使用 x-template, or the more handy Vue single file components(我真的建议您看看它们)。但无论如何,您可能需要更改应用程序的逻辑。

我遇到了同样的问题。 正如 Cobaltway 所说,由于 XSS,在您的视图中动态加载 HTML 内容是不安全的。

但是..如果你确定你的内容来源,你可以像我一样:

在我的 loadPage(target) 函数中,我总是销毁我的 vue 实例并重新创建它。

所以..你可以像这样创建你的 vue:

let content_vue_set = {
    el: '#content',
    // And all your stuff here (data, methods, watchers, etc.)
};
let content_vue = new Vue(content_vue_set);

然后,每次在页面中加载一些内容时,只需这样做:

content_vue.$destroy(); // To destroy the last Vue instance
$('#content').load(new_content); // Actually render the new content
content_vue = new Vue(content_vue_set); // Re-compile your vue instance

如我所说..这不是最佳解决方案,因此您可以使用其他逻辑。

希望这会有所帮助 ;-)