알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

vue Template 동적 변환 본문

Web /Vue js tip

vue Template 동적 변환

백곳 2018. 12. 3. 13:37

vue Template 동적 변환


가끔식 Template 를 동적으로 변환 하며 보여 주고 싶을때가 있는데 예를 들면 html 코드 미리보기 할때

vuejs 의 v-html 을 사용 하면 Custom tag나 표준이 아닌 tag의 경우 표현이 안됩니다.


그래서 v-runtime-template 기술을 사용 하면 됩니다.


오픈 소스 사이트  https://github.com/alexjoverm/v-runtime-template


샘플 코드 는 : https://codesandbox.io/s/884v9kq790



샘플 코드가 위와 같이 표현 됩니다.



아래는 오픈 소스 Readmd 를 퍼왔습니다.


오픈 소스 사이트에 들어 가면 좀더 상세히 사용법이 나와 있습니다.


Getting Started

Install it:

npm install v-runtime-template

You must use the with-compiler Vue.js version. This is needed in order to compile on-the-fly Vue.js templates. For that, you can set a webpack alias for vue to the vue/dist/vue.common file.

For example, if you use the Vue CLI, create or modify the vue.config.js file adding the following alias:

// vue.config.js
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        vue$: "vue/dist/vue.common",
      },
    },
  },
};

And in Nuxt, open the nuxt.config.js file and extend the webpack config by adding the following line to the extend key:

// nuxt.config.js
{
  build: {
    extend(config, { isDev, isClient }) {
      config.resolve.alias["vue"] = "vue/dist/vue.common";
      // ...

Usage

You just need to import the v-runtime-template component, and pass the template you want:

<template>
	<div>
		<v-runtime-template :template="template"></v-runtime-template>
	</div>
</template>

<script>
import VRuntimeTemplate from "v-runtime-template";
import AppMessage from "./AppMessage";

export default {
  data: () => ({
    name: "Mellow",
    template: `
      <app-message>Hello {{ name }}!</app-message>
    `
  }),
  components: {
    AppMessage,
    VRuntimeTemplate
  }
};
</script>

The template you pass have access to the parent component instance. For example, in the last example we're using the AppMessage component and accessing the {{ name }} state variable.

But you can access computed properties and methods as well from the template:

export default {
  data: () => ({
    name: "Mellow",
    template: `
      <div>
        <app-message>Hello {{ name }}!</app-message>
        <button @click="sayHi">Say Hi!</button>
        <p>{{ someComputed }}</p>
      </div>
		`,
  }),
  computed: {
    someComputed() {
      return "Wow, I'm computed";
    },
  },
  methods: {
    sayHi() {
      console.log("Hi");
    },
  },
};

Limitations

Keep in mind that the template can only access the instance properties of the component who is using it. Read this issue for more information.

Comparison

v-runtime-template VS v-html

TL;DR: If you need to interpret only HTML, use v-html. Use this library otherwise.

They both have the same goal: to interpret and attach a piece of structure to a scope at runtime. The difference is, [v-html](https://vuejs.org/v2/api/#v-html) doesn't understand vue template syntax, but only HTML. So, while this code works:

<template>
	<div v-html="template"></div>
</template>

<script>
export default {
  data: () => ({
    template: `
      <a href="/mike-page">Go to Mike page</a>
    `

the following wouldn't since it uses the custom router-link component:

<router-link to="mike-page">Go to Mike page</router-link>

But you can use v-runtime-template, which uses basically the same API than v-html:

<template>
	<v-runtime-template :template="template"></v-runtime-template>
</template>

<script>
export default {
  data: () => ({
    template: `
      <router-link to="mike-page">Go to Mike page</router-link>
    `

v-runtime-template VS dynamic components (<component>)

Dynamic components have somewhat different goal: to render a component dynamically by binding it to the is prop. Although, these components are usually pre-compiled. However, the goal of v-runtime-template can be achieved just by using the component options object form of dynamic components.

In fact, v-runtime-template uses that under the hood (in the render function form) along with other common tasks to achieve its goal.

Comments