当前位置: 代码网 > it编程>前端脚本>Vue.js > vue3如何定义全局组件

vue3如何定义全局组件

2024年10月27日 Vue.js 我要评论
前言vue3 全局组件需在 main.js 中定义,参考官网中的 2 个例子,实操如下。若需构建 vue 项目,请移步 。目录如下注册全局组件// main.jsimport { createapp

前言

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”.

此处的警告在官网中已经有明确的原因描述 

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

使用构建工具

由于 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 使用构建工具,默认仅运行时

总结以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com