如何在 Pug 中定义 Vue 模板?

9
如何让Vue.js在字符串模板中识别Pug?例如:
Vue.component('my-component', {
  template: `
    div
      div`})

我看到这可以在独立模板中完成,例如:

<template lang='pug'>
  div
    div
</template>

但我想在字符串模板中使用pug。


在独立模板中使用Pug很容易找到使用方法,但是关于如何在字符串模板中使用它的信息却很少。 - luntain
我认为这不是一个选项。那些字符串模板是在客户端编译的,这将需要在那里执行 Pug 翻译步骤。 - luntain
本文介绍了在Vue.js中定义组件的不同方式,但即使阅读几次后我仍然难以理解它们之间的真正区别。如果您使用pug,则x-template是迄今为止最优越的方法。 - Graham
2个回答

12
我们在使用x-template时,在vue模板中使用pug,下面是一个shell组件:
script(type="text/x-template" id="admin-tags")
  div
    h1 Admin Tags
script.
  var AdminTags = Vue.component('admin-tags', {
    template: "#admin-tags",
    props: ["options"],
    data: function(){
      return {
      }
    }
  });

然后我们只需在父模板中包含具有组件的文件。它非常有效。

更新于04/2019:我最近开始使用vue-cli启动了一个新项目,vue-cli-plugin-pug 工作得非常好。这很容易实现:

<template lang='pug'>
  div
    h1 Home
    ul
      li A
      li B
      li C
</template>

<script>

export default {
  name: 'Home',
  data () {
    return {
    }
  }
}
</script>

不确定为什么这个回答没有被点赞,这是正确的答案。 - PirateApp
1
我已经不再期望在这里得到理性的投票了,但我很高兴能帮助别人。虽然如此,我还是很感激你说出这句话。 - Graham
尝试了你的解决方案,完美地运行了,所以点个赞,这不就是 SO 的工作方式吗 :) - PirateApp
1
好的,你正在做正确的事情。但这可能是一个愚蠢的地方。 - Graham

0

在 @Graham 的回答基础上,你也可以只使用:

//- In the Pug file
script#my-component-template(type="text/x-template")
  div
    div

然后

// In the Javascript file
Vue.component('MyComponent', {
    template: '#my-component-template',
});

如果您正在为Codepen.io编写代码示例,我认为这种方式更加清晰。Pug代码放在“HTML”框中(Vue挂载元素的外部),而Javascript代码则放在“JS”框中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接