Vue3 --- 注册全局组件方式

6,318 阅读1分钟

一、方式一

注意:Vue3中一定要有组件名称
  示例:封装组件   
    <script>
        export default {
          name: 'MyMessage'
        }
    </script>
    <script setup>
        ...
    </scrtpt>
    
    <template>
        ...  
    </template>

    <style lang="scss" scoped>
        ...
    </style>
    
1. 新建目录library/index.js
    示例:
    import MyMessage from '@/components/message/MyMessage'

    const components = [
        MyMessage
    ];

    export default {
        install: app => {
            components.forEach(component => {
                // 在app上进行扩展,app提供 component directive 函数
                // 如果要挂载原型 app.config.globalProperties 方式
                app.component(component.name, component);
            });
        }
    };
    
2. 在main.js 引入
    示例:
    import Ui from '@/library/index.js'
    const app = createApp(App)
    app.use(Ui).mount('#app')
    
3. 在组件中使用
    <template>
      <MyMessage text="手机号或密码错误" type="error"></MyMessage>
    </template>
    
    注意:
        * 不需要 import 导入
        * 可以将该种方式定义为插件

二、方式二

1. 组件封装 MyMessage.vue
    示例:
        <script setup>
            ...
        </script>

        <template>
            ...  
        </template>

        <style lang="scss" scoped>
            ...
        </style>

2. 函数式方法调用组件
    创建新目录message/index.js
        import MyMessage from "@/components/message/MyMessage"; // 引入组件
        import { createVNode, render } from 'vue' //导入需要的vue函数
        // DOM容器
        const div = document.createElement('div')// 创建一个dom容器节点div
        div.setAttribute('class', 'xtx-massage-container') // 为dom添加一个唯一标识类(无实质功能)
        document.body.appendChild(div) // 容器追加到body中
        //以上我们定义好了承装该组件虚拟dom的容器,接下来要把该组件添加到容器中,并导出为一个函数

        let timer = null  // 定时器标识(用来3秒后关闭消息提示)
        export default ({ type, text }) => {// 未来在使用函数时需要传入的组件的props属性
            const vnode = createVNode(MyMessage, { type, text }) // 将组件编译为虚拟dom节点
            render(vnode, div) // 将虚拟dom添加到div容器中
        //必要步骤以完成,以下为关闭消息提示的定时器功能
            clearInterval(timer)
            timer = setTimeout(() => {
                render(null, div)
            }, 3000)
        }
3. 使用
    * 定义hooks方法
        import MyMessage from "@/components/message/index";

        export function useMessage() {
            const error = (text) =>{
                MyMessage({
                    text: text ,
                    type: "error"
                })
            }

            return {
                error
            }
        }
    * 组件使用
        <script setup>
            import {useMessage} from "@/hooks/useMessage";
            const {error} = useMessage()

            // 方法触发
            const handleBtn = () =>{
              error('失败')
            }
        <script>