Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use VueJS 2 global components inside single file components?

Tags:

I am trying to use a globally registered component (with Vue.component) inside a single file component but I am always getting

vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the component correctly? 

For example:

main.js:

... Vue.component('my-component', {     name: 'my-component',     template: '<div>A custom component!</div>' }) ... 

home.vue:

<template>     <div>         <my-component></my-component>     </div> </template> <script>     module.exports = {         name: 'home'     } </script> 

If I register it locally, it works OK:

<template>     <div>         <my-component></my-component>     </div> </template> <script> module.exports = {     name: 'home',     components: {         'my-component': require('./my-component.vue')     } } </script> 
like image 879
J. Molinero Avatar asked Oct 30 '16 17:10

J. Molinero


People also ask

How do you put a component inside another component in Vue?

You need to create your portfolio component first e.g. in src/components/Projects/Portfolio. vue and then import it inside the script tag within your Landing.

How do I use global component in Vue?

When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app. component . import { createApp } from 'vue' import App from './App.


1 Answers

You don't need the module.exports. You can register the component globally by having this within the mycomponent.vue file.

<template>     <div>A custom component!</div> </template> <script>     export default {} </script> 

Then add to main.js

import MyComponent from './component.vue' Vue.component('my-component', MyComponent); 

or I typically register them in a 'globals' file them import that into the main.

That should then allow you to use my-component anywhere in the app.

like image 160
Bryan Kneis Avatar answered Oct 19 '22 18:10

Bryan Kneis