我正在尝试将一个Vue组件打包到一个JavaScript库中,然后使用vue-sfc-rollup在另一个项目中使用它。
我可以将组件打包,就像自述文件说的那样。然后,当我将.min.js文件复制到另一个项目中并尝试使用该组件时,我总是得到错误:
Vue warn handler: Failed to mount component: template or render function not defined.
我试图从另一个Vue组件内部使用该组件的方法如下:
import Vue from 'vue'
import MyComponent from '../lib/my-components.min.js'
Vue.use(MyComponent)
然后在components部分中:
components: {
'my-component': MyComponent
}
然后在模板中:
<my-component></my-component>
这里我漏掉了什么?在另一个项目中使用组件的正确方法是什么?
编辑:添加组件代码以响应注释。
<template>
<div class="my-component">
<p>The counter was {{ changedBy }} to <b>{{ counter }}</b>.</p>
<button @click="increment">
Click +1
</button>
<button @click="decrement">
Click -1
</button>
<button @click="increment(5)">
Click +5
</button>
<button @click="decrement(5)">
Click -5
</button>
<button @click="reset">
Reset
</button>
</div>
</template>
<script>
export default {
name: 'MyComponent', // vue component name
data() {
return {
counter: 5,
initCounter: 5,
message: {
action: null,
amount: null,
},
};
},
computed: {
changedBy() {
const {
message
} = this;
if (!message.action) return 'initialized';
return `${message?.action} ${message.amount ?? ''}`.trim();
},
},
methods: {
increment(arg) {
const amount = (typeof arg !== 'number') ? 1 : arg;
this.counter += amount;
this.message.action = 'incremented by';
this.message.amount = amount;
},
decrement(arg) {
const amount = (typeof arg !== 'number') ? 1 : arg;
this.counter -= amount;
this.message.action = 'decremented by';
this.message.amount = amount;
},
reset() {
this.counter = this.initCounter;
this.message.action = 'reset';
this.message.amount = null;
},
},
};
</script>
<style scoped>
.my-component {
display: block;
width: 400px;
margin: 25px auto;
border: 1px solid #ccc;
background: #eaeaea;
text-align: center;
padding: 25px;
}
.my-component p {
margin: 0 0 1em;
}
</style>
发布于 2020-03-15 08:06:41
我在这个堆栈溢出问题中找到了一种方法:Register local Vue.js component dynamically。
我通过实现那里所示的解决方案的一个更简单的版本来使其工作。我从外部组件中删除了component部分,然后添加了这个created()生命周期挂钩:
created() {
console.log('pages/PageHome.vue: created(): Fired!')
// From https://stackoverflow.com/questions/40622425/register-local-vue-js-component-dynamically
// "This is how I ended up importing and registering components dynamically to a component locally"
const componentConfig = require('../lib/components/my-component.js')
console.log('pages/PageHome.vue: created(): componentConfig.default = ')
console.log(componentConfig.default)
const componentName = 'my-component'
console.log('pages/PageHome.vue: componentName = ' + componentName)
this.$options.components[componentName] = componentConfig.default
}
使用require()
调用导入组件,然后通过将其添加到this.$options.components dictionary
进行本地注册。秘诀是将.default
添加到componentConfig
表达式中。这似乎没有任何正式的文档记录。
社论评论:我很惊讶Vue文档对可重用性的分发模式的关注如此之少。尽管Vue文档很棒,但这是一个明显的疏漏。
https://stackoverflow.com/questions/60687073
复制相似问题