xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Vue Component Registration All In One

Vue Component Registration All In One

Vue 注册自定义组件


<template>
  <div class="back-to-top-container">
    <!-- back-to-top-container -->
    <el-backtop target=".back-to-top-container">Back Top</el-backtop>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'BackToTop',
  // name: 'back-to-top',
};
</script>

<style>
/* fullscreen */
.back-to-top-container {
  position: absolute;
  height: 100vh;
  width: 100vw;
  overflow-x: hidden;
  overflow-y: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>


import Vue from 'vue';
// @ is an alias to /src
import BackToTop from '@/components/BackToTop.vue';
// 注册全局组件,代码分离(✅ 可以在 main.js 里面直接注册的)
Vue.component(BackToTop.name, BackToTop);
/* OR */
// Vue.use(BackToTop);



// 引入全局注册组件
import '@/global-components/GlobalBackTop.js';
Vue.use(Backtop);


<template>
  <div id="app">
    <!--  全局组件 wrapper & 名称转换 BackToTop => back-to-top -->
    <back-to-top>
      <!-- 挂载点 -->
      <router-view />
    </back-to-top>
  </div>
</template>

https://vuejs.org/v2/guide/components-registration.html#Name-Casing

Style Guide — Vue.js

https://vuejs.org/v2/style-guide/#Base-component-names-strongly-recommended

由于这些组件的使用频率很高,因此您可能希望将它们简单地全局设置,而不是将它们导入任何地方。
前缀使 Webpack 可以实现:

var requireComponent = require.context("./src", true, /Base[A-Z]\w+\.(vue|js)$/)

requireComponent.keys().forEach(function (fileName) {
  var baseComponentConfig = requireComponent(fileName)
  baseComponentConfig = baseComponentConfig.default || baseComponentConfig
  var baseComponentName = baseComponentConfig.name || (
    fileName
      .replace(/^.+\//, '')
      .replace(/\.\w+$/, '')
  )
  // 注册全局组件
  Vue.component(baseComponentName, baseComponentConfig)
})

refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-12-01 11:07  xgqfrms  阅读(74)  评论(3编辑  收藏  举报