luntain
luntain

Reputation: 4680

How to define vue template in pug?

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.

Upvotes: 10

Views: 9792

Answers (2)

Vilinkameni
Vilinkameni

Reputation: 263

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.

Upvotes: 0

Graham
Graham

Reputation: 7802

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>

Upvotes: 12

Related Questions