京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

vue3如何定义全局组件

2024-11-2 22:32| 发布者: 44f6fa4f5| 查看: 96| 评论: 0

摘要: 目次前言注册全局组件使用全局组件配置 vue 构建版本总结前言 [code]vue3[/code] 全局组件需在 [code]main.js[/code] 中定义,参考官网中的 2 个例子,实操如下。 若需构建 [code]vue[/code] 项目,请移步 vite构建v
目次

前言

[code]vue3[/code] 全局组件需在 [code]main.js[/code] 中定义,参考官网中的 2 个例子,实操如下。

若需构建 [code]vue[/code] 项目,请移步 vite构建vue3项目

目次如下

注册全局组件

[code]// main.js import { createApp } from 'vue' import App from './App.vue' // createApp 函数创建一个应用实例 const app = createApp(App) // 定义全局组件 app.component('alert-box', { template: ` <div class="demo-alert-box"> <strong>Error!</strong> <slot></slot> </div> ` }) app.component('blog-post', { props: ['postTitle'], template: ` <h3>{{ postTitle }}</h3> ` }) // mount 函数返回根组件实例 const vm = app.mount('#app') console.warn('app', app, vm);[/code]

使用全局组件

[code]// HelloWorld.vue <template> <h1>{{ msg }}</h1> <p> <a href="https://vitejs.dev/guide/features.html" rel="external nofollow" target="_blank"> Vite Documentation </a> | <a href="https://v3.vuejs.org/" rel="external nofollow" target="_blank">Vue 3 Documentation</a> </p> <button @click="state.count++">count is: {{ state.count }}</button> <p> Edit <code>components/HelloWorld.vue</code> to test hot module replacement. </p> <table> <tr v-is="'blog-post'" post-title="表格行的标题"></tr> </table> <alert-box> Something bad happened. </alert-box> <blog-post post-title="hello!"></blog-post> </template> <script setup> import { defineProps, reactive } from 'vue' defineProps({ msg: String }) const state = reactive({ count: 0 }) </script> <style scoped> a { color: #42b983; } </style>[/code]

结果全局组件未生效,且控制台打印出警告:

[code][Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias “vue” to “vue/dist/vue.esm-bundler.js”.[/code]

此处的警告在官网中已经有明白的缘故原由描述 

运行时 + 编译器 vs. 仅运行时

使用构建工具

由于 [code]main.js[/code] 中全局组件都是使用 [code]html[/code] 字符串转达到 [code]template[/code] 选项,此时就是 [code]运行时 + 编译器[/code],需要完整的构建版本,故需在 [code]vite.config.js[/code] 中配置 [code]vue[/code] 构建版本为 [code]vue.esm-bundler.js[/code]。

配置 vue 构建版本

[code]// vite.config.js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], resolve: { alias: { 'vue': 'vue/dist/vue.esm-bundler.js' }, }, })[/code]

结果如下:

总结

[code]vue3[/code] 使用构建工具,默认仅运行时

总结以上为个人履历,盼望能给大家一个参考,也盼望大家多多支持脚本之家。


来源:https://www.jb51.net/javascript/328606tm4.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-2 09:20 , Processed in 0.036474 second(s), 18 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部