How to define vue template in pug?
Asked Answered
P

2

10

How to have Vue.js recognize Pug in a String template? Example:

Vue.component('my-component', {
  template: `
    div
      div`})

I saw how this can be done in standalone templates, as in:

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

But I would like to be able to use pug in String templates.

Pea answered 16/11, 2018 at 22:16 Comment(3)
It is easy to find how to use Pug in standalone templates, but no info on how to use it in a String template.Pea
I think it is just not an option. Those String templates are compiled on the client, which would require doing Pug translation step there too.Pea
This article introduces the different ways you can define a component in Vue.js, but I struggled to understand the true differences between them even after reading it a few times. When you use pug, the x-template is by far the superior method.Equipotential
E
12

We use pug in our vue templates using x-template, here's a shell component:

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 {
      }
    }
  });

Then we just include the files with the components in the parent template. It works really well.

UPDATE 04/2019: I have recently started a new project using vue-cli and vue-cli-plugin-pug has been working very well. It's as easy as this:

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

<script>

export default {
  name: 'Home',
  data () {
    return {
    }
  }
}
</script>
Equipotential answered 17/11, 2018 at 16:56 Comment(4)
not sure why this wasnt upvoted, this is the correct answerCoronagraph
I've rather given up on expecting rational votes any more here, but I am just happy to help others. I do appreciate you saying that, though.Equipotential
tried your solution, works like a charm so upvote, isnt that how SO is supposed to work :)Coronagraph
Well, you are doing the right thing. This can be a silly place though.Equipotential
L
0

To build upon @Graham's answer, you can also use just:

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

and then

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

If you are making a Codepen.io pen for example, I think this way is cleaner. Pug goes to the "HTML" box (outside of the element you mount Vue to) and Javascript goes to "JS" box.

Louettalough answered 18/3, 2020 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.