我有一个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中实现这样的功能是可能的吗?
发布于 2019-09-27 01:50:59
应该可以在http-vue-loader中使用data: URI,如下所示:
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,但您可以修补它以仅解析相关文本的承诺。
https://stackoverflow.com/questions/58120713
复制相似问题