How to register a Vue component?

I have the following files. All I want to do is create the various components that will be introduced. How to achieve this using require.js? Here are my files:

main.js

define(function(require) { 'use strict'; var Vue = require('vue'); var myTemplate = require('text!myTemplate.html'); return new Vue({ template: myTemplate, }); }); 

myTemplate.html

 <div> <my-first-component></my-first-component> </div> 

MyFirstComponent.vue

 <template> <div>This is my component!</div> </template> <script> export default {} </script> 
+7
javascript vue-component
source share
1 answer

I assume that you are using webpack as described in the Vue.js docs, otherwise your .vue file is useless. If you don’t do this, first check how to configure the Vue Webpack application, this is what allows .vue files to be used.

 import Menubar from '../components/menubar/main.vue'; Vue.component('menubar', Menubar); 

What you add, for example. menu item globally. If you want to add a component only to a small part of your application, here is another way to do it (this is taken from inside another component, but can be used in the same way on your main Vue object):

 import Sidebar from '../../components/sidebar/main.vue'; export default { props: [""], components: { 'sidebar': Sidebar }, ... 

You can download components without a web package, but I do not recommend it if you intend to use Vue (which I highly recommend you do), it is worth looking at using webpack.

Update

Once again, really, really, really consider using webpack instead, if you're going to continue with Vue.js, the setup may be a little more annoying, but the end result and development process is better than waaaay.

In any case, here is how you would create a component without webpack, note that without webpack you cannot use .vue files, since the .vue format is part of their webpack plugin. If you do not like the solution below, you can also use, for example. ajax asks to download .vue files, I believe there is a project somewhere there that does this, but I can’t find it right now, but the end result is better with webpack than with ajax, so I still recommend going with this method.

 var mytemplate = `<div> <h1>This is my template</h1> </div>` Vue.component('mycomp1', { template: mytemplate }); Vue.component('mycomp2', { template: ` <div> Hello, {{ name }}! </div> `, props: ['name'], }); 

As you can see, this method is much more cumbersome. If you want to go with this method, I would recommend splitting all the components into your own script files and downloading all these components separately before starting your real application.

Note that `Text` is a multi-line string in javascript, so it’s a little easier to write your template.

And, as I said, there is some kind of project for downloading .vue files using ajax, but I can’t find it for life right now.

+3
source share

All Articles