Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically fetch and compile a template with Nuxt

Tags:

vue.js

nuxt.js

I want to fetch an svg from a remote and bring it to life by compiling it. With 'bring to life' I mean selecting some of it's elements by class and dynamically append a list of components into it.

Right now I just use <div v-html="svg"/> and my component looks like this:

data() {
  return {
    svg: '',
  }
},
async created() {
  let res = await axios.get(mySvgSrc)
  this.svg = res.data
}

But this doesn't allow me to bring it to life by inserting elements with vue bindings.

Thus, I would like to use dynamic components like <component :is="compName"></component> so after fetching my svg, use the result as template. Example js fiddle here.

data() {
  return {
    compName: 'someDefaultComponent',
  }
},
async created() {
  let res = await axios.get(mySvgSrc)
  Vue.component('svgComponent', { template: res.data })
  this.compName = 'svgComponent' 
}

However, nuxt keeps complaining about it not being able to compile it:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

What should I do?

1) Somehow convert the svg (string) template into a render function after fetching it?

2) Use the compiler-included build? (rather not, but if so: how does that work?)

I have the feeling that I need option 2) in order to do option 1).

EDIT

Just found v-runtime-template, not sure if it's the vue way-to-go though...

like image 915
Raymundus Avatar asked Oct 29 '25 17:10

Raymundus


1 Answers

You need to change Vue build. Add this string:

config.resolve.alias['vue'] = 'vue/dist/vue.common'

to nuxt.config.js here:

build: {
  /*
  ** You can extend webpack config here
  */
  extend(config, ctx) {
    config.resolve.alias['vue'] = 'vue/dist/vue.common'
like image 136
Timofey Avatar answered Oct 31 '25 08:10

Timofey