preface
Why encapsulate global components?
It needs to be used multiple times in a project, encapsulated once, used globally. It caters to the modular development philosophy of ES6.Copy the code
How to encapsulate global components
To centrally manage global components, it is recommended that all encapsulated global components be stored in a special folder under the SRC root, such as SRC/Components. Note: XXX, folder names, and file names ending in. Vue in the example can be customized.
1. The method one
Code demo
The code is as follows (example) : Create a XXX folder in the SRC/Components folder, and create index.vue in the XXX folder
<template> <div> Custom global component </div> </template>Copy the code
Introduced in main.js and registered as a global component.
// omit others
/ / introduction
importComponent namefrom '@/components/xxx'
// Register as global component
Vue.component('Component name', component name)Copy the code
2. 2
Train of thought
Vue Router, Vuex and Vue server render can accept a single object. Vue. Use (obj) object obj requires an install function. The install function is automatically called and passed into the Vue constructorCopy the code
Code demo
The code is as follows: In the SRC/Components folder, create the yyy folder, and create the index.vue file in the YYy folder
<template> <div> Registers the global component by registering the plug-in.Copy the code
Create a new index.js file in the SRC/Components folder
// Import the written global component
importComponent name1 from './xxx'
importComponent name2 from './yyy'
// Export plug-ins by default
export default {
install: function(Vue) {
console.log('Custom plugins ~')
// Register as a global component in a custom plug-in
Vue.component('Component name 1',xxx)
Vue.component('Component name 2',yyy)
// You can also add attributes or methods to the Vue prototype object with custom names
// In other.vue ending files, you can use this to access attributes and methods you have added
Vue.prototype.num = 10
Vue.prototype.$sayHi = () = > {
alert('Hi~')}}}Copy the code
In the main.js file, use the plug-in.
import Vue from 'vue'
// Import the written custom plug-in
import myCom from '@/components'
Vue.use(myCom)
Copy the code
advantages
You can enhance the functions of Vue by registering plug-ins to uniformly register global componentsCopy the code
conclusion
Today summed up here, remember to collect oh ~ forget how to use come back Chou Chou