使用 vanilla JS 生成 Vue 组件
Generate Vue Component with vanilla JS
我目前正在使用 bootstrap table 组件来显示列表 (bootstrap-table.com)
此组件(或包裹在 vue 组件中的 jQuery 插件)每一列都有一个格式化程序。
源代码示例:https://examples.bootstrap-table.com/#welcomes/vue-component.html#view-source
我需要构建一组更复杂的链接,其中涉及一些可以使用 vue 轻松完成的 js 处理。
我想 return <component>
的内容,而不是格式化程序 returning <a>
标签。我已经试过了,但无法渲染组件。
我几乎可以肯定这是不可能的,因为子组件之前没有绑定,这意味着该组件不会 "reactive"。
作为替代方案,我可以构建一个生成所有必需链接的 js 函数。
这个问题的另一个措辞是:是否有可能从 vanilla js 生成 vue 组件?
上面的方法是不可能的,因为组件不能像 html 标签那样简单地呈现,因为它们可以有方法和计算数据,因此必须编译它们。
看来上述情况的解决方案是使用Vue.compile()
方法:
const template = `
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>`;
const compiledTemplate = Vue.compile(template);
new Vue({
el: '#app',
data() {
return {
items: ['Item1', 'Item2']
}
},
render(createElement) {
return compiledTemplate.render.call(this, createElement);
}
});
演示:
https://codepen.io/couellet/pen/ZZNXzy
我目前正在使用 bootstrap table 组件来显示列表 (bootstrap-table.com)
此组件(或包裹在 vue 组件中的 jQuery 插件)每一列都有一个格式化程序。
源代码示例:https://examples.bootstrap-table.com/#welcomes/vue-component.html#view-source
我需要构建一组更复杂的链接,其中涉及一些可以使用 vue 轻松完成的 js 处理。
我想 return <component>
的内容,而不是格式化程序 returning <a>
标签。我已经试过了,但无法渲染组件。
我几乎可以肯定这是不可能的,因为子组件之前没有绑定,这意味着该组件不会 "reactive"。
作为替代方案,我可以构建一个生成所有必需链接的 js 函数。
这个问题的另一个措辞是:是否有可能从 vanilla js 生成 vue 组件?
上面的方法是不可能的,因为组件不能像 html 标签那样简单地呈现,因为它们可以有方法和计算数据,因此必须编译它们。
看来上述情况的解决方案是使用Vue.compile()
方法:
const template = `
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>`;
const compiledTemplate = Vue.compile(template);
new Vue({
el: '#app',
data() {
return {
items: ['Item1', 'Item2']
}
},
render(createElement) {
return compiledTemplate.render.call(this, createElement);
}
});
演示: https://codepen.io/couellet/pen/ZZNXzy