首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串动态注册Vue.js组件

从字符串动态注册Vue.js组件
EN

Stack Overflow用户
提问于 2019-09-27 00:02:28
回答 1查看 682关注 0票数 1

我有一个CRUD,它使我能够在文本区域中编写Vue.js组件的代码,如下所示:

代码语言:javascript
复制
<template>
<div><p class='name-wrapper'>{{ model.name }}</p></div>
</template>
<script>
module.exports = {
  name: 'NameWrapper',
  props: ['model']
}
</script>
<style lang='sass'>
.name-wrapper
  color: red
</style>

然后在其他组件中,我获取此数据并希望将其注册为动态/异步、自定义组件,如下所示:

代码语言:javascript
复制
<template>
<component :is='dynamicName' :model='{name: "Alex"}'></component>
</template>
<script>
import httpVueLoader from 'http-vue-loader'
import Vue from 'vue'

export default {
name: 'DynamicComponent',
props: ['dynamicName', 'componentDefinitionFromTextareaAsString'],
beforeCreate: {
  // I know that as a second parameter it should be an url to the file, but I can't provide it, but I would like to pass the contents of the file instead there:
  httpVueLoader.register(Vue, this.$options.propsData.componentDefinitionFromTextareaAsString)
  // I was trying also:
  Vue.component(this.$options.propsData.dynamicName, this.$options.propsData.componentDefinitionFromTextareaAsString)
}
}
</script>

据我所知,httpVueLoader需要的是.vue文件的url --有没有办法把组件的代码传给它呢?

我知道传递和评估<script></script>标记内容可能会导致安全问题,但我真的需要这样做。

我也读过关于Vue.js编译函数的文章,但它只适用于模板,而不适用于组件的代码(所以还是script标签)。

在Vue.js中实现这样的功能是可能的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-27 01:50:59

应该可以在http-vue-loader中使用data: URI,如下所示:

代码语言:javascript
复制
const vueText = `
  <template>
      <div class="hello">Hello {{who}}</div>
  </template>
 
  <script>
  module.exports = {
      data: function() {
          return {
              who: 'world'
          }
      }
  }
  <\/script>
 
  <style>
  .hello {
      background-color: #ffe;
  }
  </style>
`

const MyComponent = httpVueLoader('data:text/plain,' + encodeURIComponent(vueText))

new Vue({
  el: '#app',
  
  components: {
    MyComponent
  }
})
代码语言:javascript
复制
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/http-vue-loader@1.4.1/src/httpVueLoader.js"></script>

<div id="app">
  <my-component></my-component>
</div>

如果由于某种原因(可能是因为某个目标浏览器不支持它)而无法正常工作,那么可以通过为httpRequest打补丁来使其正常工作。参见https://www.npmjs.com/package/http-vue-loader#httpvueloaderhttprequest-url-。文档侧重于修补httpRequest以使用axios,但您可以修补它以仅解析相关文本的承诺。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58120713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档