简体   繁体   中英

Vue.js 2.0: Apply vue component rendered using v-html, compile the markup

I'm using VueJS 2.0

Is there any way to make the below render as a link?

Here is my vue component:

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

<script>
new Vue({
  data() {
    return {
      markup: '<router-link :to="{path: 'https://www.google.com'}"></router-link>',
    });
  },
});
</script>

In the above example, I want to dynamically export a piece of markup, it contains some dynamic contents, such as router-link like above.

But that content did not compile, and exports a <router-link> tag as a final result.

Any way to make it compile programmatically?

What I really want is to find a way to compile a piece of html manually. If v-html doesn`t work, Is there any other way?

v-html works only for pre-compiled html which is basically generated text. If you want do dynamically change content, simply use if conditions to render your list view based on prop that will tell you the type of the list view.

I don't think it's a good idea to save the markup in your db. It's rather more convenient to save some settings in your db and based on those to render the necessary html. (the prop type in your case). Maybe if you provide a more concrete example, some suggestions will follow. As you can see, the answers were based on your router-link example which I think is not enough to answer your question

Given that you want to render a list of links, one way to do this can be like this:

<template>
  <router-link v-for="list in lists" :to="{path: list}"></router-link>
</template>

<script>
new Vue({
  data() {
    return {
      lists: ['https://www.google.com', 'https://www.stackoverflow.com']
    });
  },
});
</script>

Edit:

You can use an approach like following as well using with the help of dynamic components .

 Vue.use(VueRouter) new Vue({ el: "#app", data: { dynamicComp: "router-link" }, });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.2.0/vue-router.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script> <div id="app"> somethind <component :is="dynamicComp" :to="{path: 'https://www.google.com'}"></component> </div>

I don't think you can instantiate Vue instances via v-html directive. You must override the default to do that, which would take lots of efforts.

If you just want dynamic links, why not try this:

data: {
  menu: []
}

and then :

<router-link v-for="item in menu" :to="item.src">{{item.name}}</router-link>

PS: Can you give an example that you must do such things? I am really interesting in what needs it would be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM