服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue 实现创建全局组件,并且使用Vue.use() 载入方式

Vue 实现创建全局组件,并且使用Vue.use() 载入方式

2021-08-19 17:18SilenceJude JavaScript

这篇文章主要介绍了Vue 实现创建全局组件,并且使用Vue.use() 载入方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

自定义vue组件,一般是局部引用的方式载入,使用的时候,在应用的组件中使用 import modulename from ‘module' 导入,在components中注册

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
 <div class="app-newsinfo">
 <h3>{{info.title}}</h3>
 <!-- 新闻评论子组件。 -->
 <comment :id="id"></comment>
 </div>
</template>
<script>
import comment from "../sub/comment.vue";
export default {
 data() {
 return {
  info: {},
  id: this.$route.query.id
 };
 },
 methods: {},
 components: {
 comment
 },
</script>

那么如果某个组件经常复用,岂不是每次在新组建中引用都要导入一次吗?是的 。这种情况下可以将组件封装成全局组件,一次导入之后,全局都可以使用。 虽然这种做法不太常见,但是这里还是将其整理出来。

1.首先创建一个文件夹loading

用来保存需要全局引用的组件,并且存放一些配置文件。

Vue 实现创建全局组件,并且使用Vue.use() 载入方式

2.创建一个loading.vue的组件。

该组件中除了组件的基础结构,并无其他内容。它的作用是用来加载准备自定义的组件,最后将loading组件加载到全局的vue中,这样就一次性完成了所有自定义组件的加载,非常方便。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
 <div class="loading"></div>
</template>
 
<script>
export default {
 data() {
 return {};
 },
 methods: {}
};
</script>
<style scoped>
</style>

3.创建自定义组件

这里以一个简单封装的mint-ui轮播图为例。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<template>
 <div class="app-turns">
 <mt-swipe :auto="4000">
  <mt-swipe-item v-for="(item,i) of list" :key="i">
  <img :src="item.img_url" @click="detail" :data-id="item.id">
  </mt-swipe-item>
 </mt-swipe>
 </div>
</template>
 
<script>
export default {
 name: "navbar",
 props: ["list"], //接收父组件数据
 data() {
 return {
 };
 },
 methods: {
 detail(e) {
  var id = e.target.dataset.id;
  var url = `/goodsinfo/${id}`;
  this.$router.push(url);
 }
 },
 created() {}
};
</script>
<style scoped>
.mint-swipe {
 height: 150px;
}
.mint-swipe img {
 width: 100%;
}
</style>

4.创建index.js,用来导出所有自定义组件。

?
1
2
3
4
5
6
7
8
9
import turns from './turns.vue'
 
const loading = {
 install: function (vue) {
 vue.component('turns', turns)
 }
}
 
export default loading;

其实到这里组件封装就结束了,下面再演示下如何使用。

5.在main.js中,导入并使用loading组件。

import loading from './lib/loading';

vue.use(loading);

这样就将组件全局引用成功了!

6.在需要使用的地方,直接使用组件名即可。

?
1
2
3
4
5
<template>
 <div class="app-home">
 <turns :list="list"></turns>
 </div>
</template>

通过这种方式,就能实现组件的全局引用。

这种做的好处是对于复用性非常高的组件,省去了每次导入的麻烦;

缺点是无法直观的看到组件引入和注册,对于不清楚的人来说看不懂组件名的意义。

其实官方文档中已经提到了一种解决方案:

https://cn.vuejs.org/v2/guide/components-registration.html#基础组件的自动化全局注册

基础组件的自动化全局注册

可能你的许多组件只是包裹了一个输入框或按钮之类的元素,是相对通用的。我们有时候会把它们称为基础组件,它们会在各个组件中被频繁的用到。

所以会导致很多组件里都会有一个包含基础组件的长列表:

?
1
2
3
4
5
6
7
import basebutton from ‘./basebutton.vue' import baseicon from
‘./baseicon.vue' import baseinput from ‘./baseinput.vue'
 
export default { components: {
basebutton,
baseicon,
baseinput } }

而只是用于模板中的一小部分:

<baseinput v-model=“searchtext” @keydown.enter=“search” />

<basebutton @click=“search”>

幸好如果你使用了 webpack (或在内部使用了 webpack 的 vue cli 3+),那么就可以使用 require.context 只全局注册这些非常通用的基础组件。这里有一份可以让你在应用入口文件 (比如 src/main.js) 中全局导入基础组件的示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import vue from ‘vue' import upperfirst from ‘lodash/upperfirst'
import camelcase from ‘lodash/camelcase'
 
const requirecomponent = require.context( // 其组件目录的相对路径
‘./components', // 是否查询其子目录 false, // 匹配基础组件文件名的正则表达式
/base[a-z]\w+.(vue|js)$/ )
 
requirecomponent.keys().foreach(filename => { // 获取组件配置 const
componentconfig = requirecomponent(filename)
 
// 获取组件的 pascalcase 命名 const componentname = upperfirst(
camelcase(
// 剥去文件名开头的 ./ 和结尾的扩展名
filename.replace(/^./(.*).\w+$/, ‘$1')
) )
 
// 全局注册组件 vue.component(
componentname,
// 如果这个组件选项是通过 export default 导出的,
// 那么就会优先使用 .default,
// 否则回退到使用模块的根。
componentconfig.default || componentconfig ) })

补充知识:vue组件注册 vue.extend vue.component vue.use的使用 以及组件嵌套

我就废话不多说了,大家还是直接看代码吧~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 *  vue.extend用法
 *  使用基础 vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。
 *  注意:此实例可以挂载到根实例之外
 */
 
 const profile = vue.extend({
 template: '<p>{{firstname}} {{lastname}} aka {{alias}}</p>',
 data: function () {
  return {
  firstname: 'walter',
  lastname: 'white',
  alias: 'heisenberg'
  }
 }
 })
 // 创建 profile 实例,并挂载到一个元素上。
 new profile().$mount('#opp')
 
let navbar = {
 template: `<div class='nav'>
     <input type="text" placeholder="请输入关键字"/>
    </div>`,
 data:()=>{
  return {
  }
 },
 mounted() {
  console.log(this.$parent)
 }
};
 
const myplugin = {
 install:(vue, arguments)=>{
  console.log(arguments);
  vue.component('navbar', navbar);
 }
}
 
vue.use(myplugin, {a:1, b:2}); // 组件注册成功
 
// logo组件
vue.component("logo", {
 template: `<div class='logo'>
     <img v-bind:src="logosrc">
    </div>`,
 inject: ['logosrc'], 
 data:()=>{
  return {
  }
 },
 mounted() {
  console.log(this.$parent)
 }
})
// header组件 组件调用 provie inject传值
vue.component("buttoncounter", {
 template: `<div class='header'>
    <logo></logo>
    {{header}}
    </div>`,
 provide:{
  logosrc:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582433251882&di=de459decf2e157552b97a4879ae4135d&imgtype=0&src=http%3a%2f%2fwww.suntop168.com%2fblog%2fzb_users%2fupload%2f2014%2f2%2fadf89182.jpg'
 },
 data:()=>{
  return {
   header:'我是头部导航栏'
  }
 },
 mounted() {
  console.log(this.$parent)
 }
});
 
// vue根实例
let vm = new vue({
 el:"#app",
 data:{
  name: 'marry'
 },
 mounted(){
  console.log('vue根实例初始化完毕')
 }
})
 
console.log(vm);

以上这篇vue 实现创建全局组件,并且使用vue.use() 载入方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/SilenceJude/article/details/85088764

延伸 · 阅读

精彩推荐