使用 Nuxt 动态获取和编译模板 [英] Dynamically fetch and compile a template with Nuxt

查看:29
本文介绍了使用 Nuxt 动态获取和编译模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从远程获取一个 svg 并通过编译使其栩栩如生.赋予生命"是指按类选择其中的一些元素,并动态地将组件列表附加到其中.

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.

现在我只使用 <div v-html="svg"/> 并且我的组件看起来像这样:

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
}

但这不允许我通过插入带有 vue 绑定的元素来实现它.

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

因此,我想使用像 <component :is="compName"></component> 这样的动态组件,因此在获取我的 svg 后,将结果用作模板.示例 js fiddle here.

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' 
}

然而,nuxt 一直抱怨无法编译它:

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

[Vue 警告]:您正在使用 Vue 的仅运行时构建,其中模板编译器不可用.要么预编译模板进入渲染函数,或使用编译器包含的构建.

[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.

我该怎么办?

1) 获取后以某种方式将 svg(字符串)模板转换为渲染函数?

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

2) 使用编译器包含的构建?(而不是,但如果是这样:它是如何工作的?)

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

我觉得我需要选项 2) 才能执行选项 1).

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

刚找到v-runtime-template,不知道是不是vue虽然要走...

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

推荐答案

您需要更改 Vue 构建.添加此字符串:

You need to change Vue build. Add this string:

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

到nuxt.config.js这里:

to nuxt.config.js here:

build: {
  /*
  ** You can extend webpack config here
  */
  extend(config, ctx) {
    config.resolve.alias['vue'] = 'vue/dist/vue.common'

这篇关于使用 Nuxt 动态获取和编译模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆