vue3如何定義全局組件
前言
vue3 全局組件需在 main.js 中定義,參考官網(wǎng)中的 2 個例子,實(shí)操如下。
若需構(gòu)建 vue 項(xiàng)目,請移步 vite構(gòu)建vue3項(xiàng)目。
目錄如下

注冊全局組件
// main.js
import { createApp } from 'vue'
import App from './App.vue'
// createApp 函數(shù)創(chuàng)建一個應(yīng)用實(shí)例
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 函數(shù)返回根組件實(shí)例
const vm = app.mount('#app')
console.warn('app', app, vm);使用全局組件
// HelloWorld.vue
<template>
<h1>{{ msg }}</h1>
<p>
<a rel="external nofollow" target="_blank">
Vite Documentation
</a>
|
<a 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="表格行的標(biāo)題"></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>
結(jié)果全局組件未生效,且控制臺打印出警告:
[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”.
此處的警告在官網(wǎng)中已經(jīng)有明確的原因描述

使用構(gòu)建工具

由于 main.js 中全局組件都是使用 html 字符串傳遞到 template 選項(xiàng),此時就是 運(yùn)行時 + 編譯器,需要完整的構(gòu)建版本,故需在 vite.config.js 中配置 vue 構(gòu)建版本為 vue.esm-bundler.js。
配置 vue 構(gòu)建版本
// 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'
},
},
})效果如下:

總結(jié)
vue3 使用構(gòu)建工具,默認(rèn)僅運(yùn)行時
總結(jié)以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
客戶端(vue框架)與服務(wù)器(koa框架)通信及服務(wù)器跨域配置詳解
本篇文章主要介紹了客戶端(vue框架)與服務(wù)器(koa框架)通信及服務(wù)器跨域配置詳解,具有一定的參考價值,有興趣的可以了解一下2017-08-08
Vue預(yù)覽圖片和視頻的幾種實(shí)現(xiàn)方式
本文主要介紹了Vue預(yù)覽圖片和視頻的幾種實(shí)現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
vue自定義組件實(shí)現(xiàn)v-model雙向綁定數(shù)據(jù)的實(shí)例代碼
vue中父子組件通信,都是單項(xiàng)的,直接在子組件中修改prop傳的值vue也會給出一個警告,接下來就用一個小列子一步一步實(shí)現(xiàn)了vue自定義的組件實(shí)現(xiàn)v-model雙向綁定,需要的朋友可以參考下2021-10-10
Vue Cli項(xiàng)目重構(gòu)為Vite的方法步驟
本文主要介紹了Vue Cli項(xiàng)目重構(gòu)為Vite的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04

