Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get template as string in Vue

Say, I have the following single file component in Vue:

// Article.vue

<template>
  <div>
    <h1>{{title}}</h1>
    <p>{{body}}</p>
  </div>
</template>

After importing this component in another file, is it possible to get its template as a string?

import Article from './Article.vue'

const templateString = // Get the template-string of `Article` here.

Now templateString should contain:

<div>
  <h1>{{title}}</h1>
  <p>{{body}}</p>
</div>
like image 963
Jan-Paul Kleemans Avatar asked Jan 15 '18 16:01

Jan-Paul Kleemans


People also ask

What is a string template in Vue?

String Templates You can define a template in vanilla JavaScript as a string literal or template literal. This approach means a component's HTML and JavaScript stay in the same file, which is generally considered a positive. The downside is that you don't get HTML syntax highlighting.

What is REF () in Vue?

ref() # Takes an inner value and returns a reactive and mutable ref object, which has a single property . value that points to the inner value.

What is Vue template tag?

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data. All Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

How do I use a Vue template in JavaScript?

We need to prefix the src with v-bind:src = ”imgsrc” and the name of the variable with src. Following is the output in the browser. Let us inspect and check how the src looks like with v-bind. As seen in the above screenshot, the src is assigned without any vuejs properties to it.


1 Answers

It is not possible.

Under the hood, Vue compiles the templates into Virtual DOM render functions.

So your compiled component will have a render function, but no place to look at the string that was used to generate it.

Vue is not a string-based templating engine

However, if you used a string to specify your template, this.$options.template would contain the string.

like image 171
Roy J Avatar answered Sep 18 '22 11:09

Roy J