前言
vue3 全局组件需在 main.js 中定义,参考官网中的 2 个例子,实操如下。
若需构建 vue 项目,请移步 。
目录如下

注册全局组件
// 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);使用全局组件
// 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>
结果全局组件未生效,且控制台打印出警告:
[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”.
此处的警告在官网中已经有明确的原因描述

使用构建工具

由于 main.js 中全局组件都是使用 html 字符串传递到 template 选项,此时就是 运行时 + 编译器,需要完整的构建版本,故需在 vite.config.js 中配置 vue 构建版本为 vue.esm-bundler.js。
配置 vue 构建版本
// 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'
},
},
})效果如下:

总结
vue3 使用构建工具,默认仅运行时
总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论