简体   繁体   中英

Vue plugin doesn't work when directly imported in Components

i created a simple vue plugin

import myComp from "./myComp.vue";
export default {
    install(Vue, options) {
       Vue.component("my-plugin", myComp);
    }
}

and imported it in main.js

import MyPlugin from './myPlugin.js'
Vue.use(MyPlugin)

and everything is ok and i can use it anywhere, but when i want to use it in specific Component like this

<template>
  <div>
    <my-plugin></my-plugin>
   </div>
</template>
<script>
import MyPlugin from './../myPlugin.js'
export default {
   MyPlugin
}
</script>

i get this error in console

vue.runtime.esm.js?2b0e:619 [Vue warn]: 
Failed to mount component: template or render function not defined.

found in

---> <MyPlugin>
       <AppHome> at src/components/Home.vue
         <App> at src/App.vue
           <Root>

whats my problem guys how i can resolve it? thanks

Here is a sample code to register globally components.

There is something tricky, probably the global component registration before the first Vue instance.

main.js

import Vue from "vue";
import App from "./App";
import my_plugin from "./my-plugin";

Vue.use(my_plugin);
new Vue({
    el: "#app",
    render: h => h(App),
});

my-plugin.js

import MyComp from "./MyComp";

export default {
    install(VueInstance) {
        VueInstance.component("MyComp", MyComp);
    }
}

MyComp.vue

<template>
    <div>{{this.message}}
        <my-comp v-if="this.index>0" :index="this.index-1" :message="message">
        </my-comp>
    </div>
</template>
<script>
    export default {
        name: "MyComp",
        props:['index','message'],
        components: {},
        data: function () {
            return {}
        }
    }
</script>

App.vue: with no import of my-comp

<template>
    <div>
        <MyComp index="4" message="static"></MyComp>
        <component :is="'my-comp'" index="4" message="dynamic"/>
    </div>
</template>
<script>
    export default {
        name: "App",
        components: {},
        data: function () {
            return {}
        }
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM