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

标签 javascript vue.js vuejs2 compilation http-vue-loader

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

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

然后在其他组件中,我获取此数据并想将其注册为动态/异步自定义组件,例如:

<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 中实现这样的功能吗?

最佳答案

应该可以将 data: URI 与 http-vue-loader 一起使用,如下所示:

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
  }
})
<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,但您可以修补它以仅解决对相关文本的 promise 。

关于javascript - 从字符串动态注册 Vue.js 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120713/

相关文章:

JavaScript 将数组与数组对象进行比较以查看它们的值是否匹配

javascript - eval() 表达式中包含 "return"

vue.js - Vuetify - 自定义文本时如何将复选框包含到 v-select

node.js - Vuex 和 Websocket

vue.js - 如何在 gridsome 中添加和使用 vue-confetti

javascript - 向上或向下滚动时 Div/Box 出现问题

javascript - 从函数调用返回值时,最新的 JavaScript/ECMAScript 编译器是否会优化不必要的变量赋值?

javascript - v-for 与子对象

javascript - 如何过滤数据对象?

javascript - 如何添加此代码以使我的表格列可在单击时排序?