最简单的使用,在 main.js 编写如下代码,即可将 xxx 组件在每个页面显示

// main.js
// 引入组件
import xxx from "@/components/xxx.vue";
// 将该组件挂载在document.body下
document.body.appendChild(new xxx().$mount().$el);

函数式调用全局组件方法

场景,某些 toast 组件需要如下方式使用

<template>
    <toast ref="toast"></toast>
</template>
<script>
    export default {
        methods:{
            showToast(){
                this.$refs.toast.show();
            }
        }
    }
</script>

经改造,最终使用方法为:

this.$r.toast().show();

实现方式:

1、在 utils 目录下新建 render.js

2、在 main.js 下将 render.js 绑定在 this

// ...
import render from "@/utils/render";
Vue.prototype.$r = render;
// ...

3、在 render.js 内将组件绑定至全局

// utils/render.js
// 引入vue
import vm from "vue";
// toast组件
import toast from "@/components/xxx/toast.vue";
export default {
    /**
     * 全局toast弹窗    
    */
    toast(){
        // 全局注册toast组件
        const toastCom = vm.component('toast',toast);
        // 获取uniapp根节点
        const uniappRoot = document.getElementsByTagName("uni-app")[0];
        // 初始化toast组件
		const toastComp = new toastCom();
        // 这里我每个组件内都有一个固定id,用来禁止同意组件生成多次
		if(document.getElementById(toastComp.id)){
			document.getElementById(toastComp.id).remove();
		}
        // 将toast组件添加在uniapp根节点上
		uniappRoot.appendChild(toastComp.$mount().$el);
		return toastComp;
    }
}

4、最后我们可以直接函数式调用组件方法与设置组件属性

// 此show方法在toast组件的methods中定义
this.$r.toast().show();
// 此duration属性在toast组件的data中
this.$r.toast().duration;

嘿,愿你代码永无bug,人生永无坎坷!

嘿,愿你代码永无bug,人生永无坎坷!

嘿,愿你代码永无bug,人生永无坎坷!

嘿,愿你代码永无bug,人生永无坎坷!

嘿,愿你代码永无bug,人生永无坎坷!

嘿,愿你代码永无bug,人生永无坎坷!

广告:(提供学习机会)

       前端交流学习群:1063233592

       PHP学习交流群:901759097

       前后端学习交流微信群:加我微信,填写验证消息(前端),拉你进群

uniapp全局组件全局使用(不在每个页面template使用,仅支持H5),函数式调用全局组件方法

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。