【问题标题】:different ways to render Vue template from a variable without vue router从没有 vue 路由器的变量中渲染 Vue 模板的不同方法
【发布时间】:2018-01-23 22:46:21
【问题描述】:

我目前正在使用 Vue JS,但我没有使用任何路由器。我没有使用独立构建,而是希望使用 webpack 实现并将其与 .vue 扩展名一起使用。寻找使用变量呈现 Vue 模板的更好方法。例如:

// App.Vue
var Loading = {
   template: `<div>Loading...</div>`
}

// main.js
var currentView = Loading;

new Vue({
  el: "#app",
  render(h) {
    return h(currentView);
  }
});

上面的例子完全没有问题。想了解是否有更好的处理方法。

假设 currentView 是否包含类似

的字符串
currentView = "Loading"

render(h) {
  return h(eval(currentView)); // works
  return h([currentView]); // template not found or mount error 
}

我们如何在模板传递给渲染函数之前将值替换为模板?

提前致谢。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    h 是 Vue 的 createElement 用于创建虚拟 Dom 元素。与浏览器的 createElement 相同,用于创建真正的 Dom 元素。所以它只适用于虚拟 Dom 而不是字符串。如果你想要你的第二个示例工作,你必须注册一个名为“Loading”的组件。

    var Loading = {
       template: `<div>Loading...</div>`
    }
    
    // main.js
    var currentView = "Loading";
    
    new Vue({
      el: "#app",
      render(h) {
        return h(currentView);
      },
      components: {
         Loading: Loading //register Loading component as "Loading"
      }
    });
    

    或者注册为全局Loading组件

    Vue.component("Loading", Loading);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2017-09-16
      • 2021-02-02
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多