vue3如何定義全局組件
前言
vue3
全局組件需在 main.js
中定義,參考官網(wǎng)中的 2 個例子,實操如下。
若需構(gòu)建 vue
項目,請移步 vite構(gòu)建vue3項目。
目錄如下
注冊全局組件
// main.js import { createApp } from 'vue' import App from './App.vue' // createApp 函數(shù)創(chuàng)建一個應(yīng)用實例 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ù)返回根組件實例 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="表格行的標題"></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
選項,此時就是 運行時 + 編譯器
,需要完整的構(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)建工具,默認僅運行時
總結(jié)以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
客戶端(vue框架)與服務(wù)器(koa框架)通信及服務(wù)器跨域配置詳解
本篇文章主要介紹了客戶端(vue框架)與服務(wù)器(koa框架)通信及服務(wù)器跨域配置詳解,具有一定的參考價值,有興趣的可以了解一下2017-08-08vue自定義組件實現(xiàn)v-model雙向綁定數(shù)據(jù)的實例代碼
vue中父子組件通信,都是單項的,直接在子組件中修改prop傳的值vue也會給出一個警告,接下來就用一個小列子一步一步實現(xiàn)了vue自定義的組件實現(xiàn)v-model雙向綁定,需要的朋友可以參考下2021-10-10