首页 > 其他分享 >Auto-registering all your components in Vue 3 with Vite

Auto-registering all your components in Vue 3 with Vite

时间:2023-08-13 16:55:25浏览次数:43  
标签:Vue registering Auto component vue components Fruits import

Auto-registering all your components in Vue 3 with Vite

#vue#vitejs#components

Why auto-register components?

I'm actually a big fan of manually importing components in Vue applications. It makes it very clear where every component comes from, doesn't rely on ✨magic✨, and most IDEs can do auto-imports for you anyway so it's not much more work for you.

That said, in an environment where I'm not building an SPA, and I'm using Vue as a progressive enhancement tool, I want all of my components to be available in HTML. To make this happen, I have to register all of them in the root Vue instance....

import { createApp } from 'vue'
// import each component
import Fruits from './components/Fruits.vue'
import Vegetables from './components/Vegetables.vue'

const vueApp = createApp({
  // register each component
  components: { Fruits, Vegetables }
})
 

This process is tedious, and makes component auto-registration totally worth it IMO.

How

So, to auto-register our components, we need to do a few things:

  1. Get a list of each component
  2. Import that component
  3. Register it on our Vue instance

Luckily, Vite has an amazing feature which takes care of steps #1 and #2 for us

Step 1+2: Glob Imports.

Glob Imports is feature of Vite that allows us to import multiple files based on a filepath.

There are two ways to use Glob Imports in Vite: lazy or eager. If you use the standard glob method, the imports will be processed as dynamic imports, so the components will be lazy-loaded. In our case, we want to import all of the components directly into our main bundle, so we'll use the globEager method.

Note: Glob Imports is a Vite feature, and is not part of any JS or "platform" standards.

Here's how Glob Imports works:

// import multiple components
const components = import.meta.globEager('./components')
 

And here's the result of that import:

// code produced by vite

// magically autogenerated module imports
import * as __glob__0_0 from './components/Fruits.vue'
import * as __glob__0_1 from './components/Vegetables.js'

// our components variable now contains an object with key/values
// representing each module's path and definition
const components = {
  './components/Fruits.vue': __glob__0_0,
  './components/Vegetables.vue': __glob__0_1
}
 

Step 3: Registering components

Now that we've actually imported each component, and we have a list containing the path and definition, we need to define these components on our Vue instance.

To do that, we'll loop over each entry in our components object, figure out the component's name based on the file name, and then register the component on our Vue instance.

Object.entries(components).forEach(([path, definition]) => {
  // Get name of component, based on filename
  // "./components/Fruits.vue" will become "Fruits"
  const componentName = path.split('/').pop().replace(/\.\w+$/, '')

  // Register component on this Vue instance
  vueApp.component(componentName, definition.default)
})
 

Putting it all together

import { createApp } from 'vue'

const vueApp = createApp()

const components = import.meta.globEager('./components/*.vue')

Object.entries(components).forEach(([path, definition]) => {
  // Get name of component, based on filename
  // "./components/Fruits.vue" will become "Fruits"
  const componentName = path.split('/').pop().replace(/\.\w+$/, '')

  // Register component on this Vue instance
  vueApp.component(componentName, definition.default)
})

标签:Vue,registering,Auto,component,vue,components,Fruits,import
From: https://www.cnblogs.com/mouseleo/p/17626805.html

相关文章

  • Vue中出现“‘xxxxx‘ is defined but never used”解决办法
    【解决办法】:在package.json或者.eslintrc.js中找到 eslintConfig 块,在其rules下加入"no-unused-vars":"off"即可,如下图然后重新npmrunserve即可。其他命令如下:"no-alert":0,//禁止使用alertconfirmprompt"no-array-constructor":2,//禁止使用数组构造器"no-bitwis......
  • vue--day62--配置代理
    前端发送ajax请求的方式1.xhrnewXMLHttpRequestxhr.open()xhr.send()基本不用2.jquery(封装的xhr)$get$post3.axios(封装的xhr)和jquery比较promise风格的,支持请求拦截器和响应拦截器是jquery的1/4体积小4.fetch(和xhr是同级别的)也是promise......
  • 【技术实战】Vue功能样式实战【七】
    需求实战一样式展示代码展示<template><transitionname="fade-in"appear><ARowv-if="show"><ACol><divclass="info-card"><divclass="in......
  • vue项目部署到gitee
    1、首先本地项目生成静态网页npmrunbuild使用本命令将vue项目打包成静态网页存放到dist文件夹里2、将静态资源推到gitee仓库前提条件:新建了git仓库,然后 gitclone +仓库地址,拉到本地,将dist整个文件夹放到刚才拉下来的项目文件夹中。gitadddistgitcommit-m"部署......
  • 究极鬼畜:泛型auto
    究极鬼畜:泛型auto零前言C++作为一门强大的语言,标准库中为我们提高了许多相当实用的模板。然而有时候你(其实整个机房就我一个)又自己有一些代码,想转化为一个封装好的板子。这时候,你就不得不接触泛型编程了。那个auto是为了押韵乱加的,虽然auto确实可以用来泛型……由于......
  • 【技术实战】Vue功能样式实战【六】
    需求实战一样式展示代码展示<template><ARow><AColstyle="background-color:#F1F4F5"><divclass="info-card"><divclass="info-title">数据总和......
  • Vue学习笔记:路由开发 Part 08 导航守卫
    vue-router提供的导航守卫主要用来通过跳转或取消的方式守卫导航。这里有很多方式植入路由导航中:全局的,单个路由独享的,或者组件级的。全局前置守卫可以使用 router.beforeEach 注册一个全局前置守卫。当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航......
  • VUE3_API 风格
    选项式API(OptionsAPI)使用选项式API,我们可以用包含多个选项的对象来描述组件的逻辑,例如 data、methods 和 mounted。选项所定义的属性都会暴露在函数内部的 this 上,它会指向当前的组件实例<script>exportdefault{//data()返回的属性将会成为响应式的状态/......
  • Autodesk Maya 2017三维动画软件下载和安装教程
    AutodeskMaya是Autodesk公司出品的世界顶级的三维动画软件,应用对象是专业的影视广告,角色动画,电影特技等。Maya功能完善,工作灵活,易学易用,制作效率极高,渲染真实感极强,是电影级别的高端制作软件。软件介绍加入了漫游工具(WalkTool)。使用快捷键Alt+X开启这个模式后,按住鼠标左右键,然后......
  • 使用create-vue创建vue3项目
    create-vue是vue3新的脚手架搭建项目工具,底层构建工具使用vite,而不是vue-cli的webpack。但不是说你不能用以前的vuecreate命令来创建vue3项目,你完全可以用vue-cli来创建。vite:https://cn.vitejs.dev/guide/#scaffolding-your-first-vite-project使用create-vue创建项目使用cr......