Vue全局组件的注册与使用

今天我们来探究一下Vue全局组件的注册与使用。基于个人的开发经验,全局组件相比局部组件来说,使用的频率还是低不少的。所以在全局组件的使用上,我个人来说比较模糊,遂打算一探究竟,并记录下来。

第1步

我们先写一个全局组件,以供使用。

// now-time.vue
<template>
  <div>
    当前时间为:{{ nowTime }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      nowTime: new Date()
    }
  }
}
</script>
<style></style>
第2步

对全局组件进行注册。在此我们有两种注册方式。

以下代码均写在main.js

第一种注册方式:
// main.js

// 引入组件文件
import NowTime from './components/NowTime/now-time.vue'
// 直接使用Vue.component 对组件进行注册, 该组件名就是 Vue.component 的第一个参数
Vue.component('now-time', NowTime)

注册过后,即可在任意页面直接使用

<!-- 任意页面.vue -->
<now-time></now-time>
第二种注册方式:

我们需要在NowTime文件夹下新建一个index.js文件,文件目录如下:

Rgbc3n.png

// index.js
import NowTime from './now-time.vue'

const NowTimeComponent = {
  install: (Vue) => {
    Vue.component('now-time', NowTime)
  }
}
export default NowTimeComponent

然后在main.js文件中进行注册

// main.js
import NowTime from './components/NowTime/index.js'
Vue.use(NowTime)

注册完成即可在任意页面使用了。

可能有的同学会问,这第二种注册方式看起来比第一种繁琐多了,还得写一个index.js,为什么要用这种呢?

接下来我们说说这第二种注册方式的优点:它可以在注册组件的时候,给组件传入一些通用的属性。例如:字体大小、颜色等。具体看如下代码:

我们在组件中设置字体颜色,颜色来源为this.$NOWTIME.color

// now-time.vue
<template>
  <div :style="{ color: color}">
    当前时间为:{{ nowTime }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      nowTime: new Date(),
      color: this.$NOWTIME.color
    }
  }
}
</script>
<style></style>

index.js中的install()方法的第一个参数为Vue实例,第二个参数为我们在注册时传入的参数。在此处是一个对象,我们可在该对象中设置一些具体的属性。

// index.js
import NowTime from './now-time.vue'

const NowTimeComponent = {
  install: (Vue, otps = {}) => {
    Vue.component('now-time', NowTime)
    Vue.prototype.$NOWTIME = {
      color: otps.color || ''
    }
  }
}

export default NowTimeComponent

main.js中注册组件,在Vue.use()方法中传入参数,此处传入color: 'blue',组件的字体颜色即为blue

// main.js
import NowTime from './components/NowTime/index.js'
Vue.use(NowTime, {
  color: 'blue'
})
结语

记住全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生

全局注册往往是不够理想的。比如,如果你使用一个像 webpack 这样的构建系统,全局注册所有的组件意味着即便你已经不再使用一个组件了,它仍然会被包含在你最终的构建结果中。这造成了用户下载的 JavaScript 的无谓的增加。

  • 13
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值