vue中组件的局部注册和全局注册

vue中组件的局部注册和全局注册

组件的注册可以分为,全局注册和局部注册。

局部注册

局部注册,只能在注册的组件中使用。

在当前项目的src目录下,创建components文件夹用于存放组件。然后再components文件夹中创建组件(xxx.vue)。

  1. 组件的声明定义 : 创建 RobinHeader.vue
<template>
  <div class="robin-header">
        robin debug
  </div>
</template>

<script>
export default {

}
</script>

<style>
    .robin-header{
        height: 60px;
        width: 580px;
        text-align: center;
        line-height: 60px;
        color:white;
        font-size: 22px;
        margin: 0 auto;
        background-color: lightskyblue;
    }
</style>
  1. 组件的注册在App.vue中注册,即只在根组件中使用
<template>
  <div class="App">
    <RobinHeader></RobinHeader>
  </div>
</template>

<script>
// 导入自定义的组件
import RobinHeader from './components/RobinHeader.vue'

export default {
  components:{
    // 组件名 : 组件对象
    RobinHeader:RobinHeader
  }
}
</script>

<style>
.App{
  width: 600px;
  height: 700px;
  margin: 0 auto;
  background: #eee;
  padding: 20px;
  border-radius: 15px;
}
</style>
  1. 项目结构图及显示结果

在这里插入图片描述

全局注册

全局注册,在所有组件中都可以使用。全局注册,需要在main.js中进行注册。

  1. 组件的声明定义:
<template>
   <button class="robin-button">
        robin - button
   </button>
</template>

<script>
export default {

}
</script>

<style>
    .robin-button{
        margin: 10px;
        width: 120px;
        padding: 5px;
        height: 40px;
        color: white;
        background: lightpink;
        border-radius: 5px;
    }
</style>
  1. 组件的全局注册:
import Vue from 'vue'
import App from './App.vue'
// 导入要全局注册的组件
import RobinButton from './components/RobinButton'
Vue.config.productionTip = false

// 全局注册
// Vue.component('组件名',组件对象)
Vue.component('RobinButton',RobinButton)
new Vue({
  render: h => h(App),
}).$mount('#app')
  1. 组件的使用:全局注册后的组件,直接使用即可,使用标签名就行。
    App.vue
<template>
  <div class="App">
    <RobinHeader></RobinHeader>
    <RobinButton></RobinButton>
  </div>
</template>

RobinHeader.vue

<template>
  <div class="robin-header">
        robin debug
    <RobinButton></RobinButton>
  </div>
</template>
  1. 项目结构及效果:

在这里插入图片描述

小结

组件的注册,全局注册和局部注册,一般组件都是局部注册,哪里用到在哪里声明即可,全局注册只有当组件很通用时,在当前项目中很多地方都用才会去全局注册。

局部注册的方式是,哪里需要就去哪里导入注册,先使用import 组件对象 from '组件相对路径'将组件导入,然后使用 components:{组件名,组件对象}的方式去注册。

全局注册的方式是,在当前项目的main.js中,使用import 组件对象 from '组件相对路径'导入,然后使用 Vue.Component('组件名',组件对象)去注册。


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杀死一只知更鸟debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值