程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

vue3定义全局组件

发布于2021-05-30 12:07     阅读(842)     评论(0)     点赞(9)     收藏(3)


前言

vue3 全局组件需在 main.js 中定义,参考官网中的 2 个例子,实操如下。若需构建 vue 项目,请移步 vite构建vue3项目
目录如下
在这里插入图片描述

注册全局组件

// 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" target="_blank">
      Vite Documentation
    </a>
    |
    <a href="https://v3.vuejs.org/" 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 使用构建工具,默认仅运行时

原文链接:https://blog.csdn.net/harmsworth2016/article/details/117266787




所属网站分类: 技术文章 > 博客

作者:小猪佩奇身上纹

链接:http://www.qianduanheidong.com/blog/article/115987/9a72e7da2c523c5ffe43/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

9 0
收藏该文
已收藏

评论内容:(最多支持255个字符)