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


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

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

    函数式调用全局组件方法

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

    1. <template>
    2. <toast ref="toast">toast>
    3. template>
    4. <script>
    5. export default {
    6. methods:{
    7. showToast(){
    8. this.$refs.toast.show();
    9. }
    10. }
    11. }
    12. script>

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

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

    实现方式:

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

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

    1. // ...
    2. import render from "@/utils/render";
    3. Vue.prototype.$r = render;
    4. // ...

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

    1. // utils/render.js
    2. // 引入vue
    3. import vm from "vue";
    4. // toast组件
    5. import toast from "@/components/xxx/toast.vue";
    6. export default {
    7. /**
    8. * 全局toast弹窗
    9. */
    10. toast(){
    11. // 全局注册toast组件
    12. const toastCom = vm.component('toast',toast);
    13. // 获取uniapp根节点
    14. const uniappRoot = document.getElementsByTagName("uni-app")[0];
    15. // 初始化toast组件
    16. const toastComp = new toastCom();
    17. // 这里我每个组件内都有一个固定id,用来禁止同意组件生成多次
    18. if(document.getElementById(toastComp.id)){
    19. document.getElementById(toastComp.id).remove();
    20. }
    21. // 将toast组件添加在uniapp根节点上
    22. uniappRoot.appendChild(toastComp.$mount().$el);
    23. return toastComp;
    24. }
    25. }

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

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

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

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

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

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

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

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

     

    广告:(提供学习机会)

           前端交流学习群:1063233592

           PHP学习交流群:901759097

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

  • 相关阅读:
    信息系统项目管理师-沟通管理论文提纲
    C. Planar Reflections
    自动化测试框架pytest命令参数
    YOLOv8-Seg推理详解及部署实现
    Springboot晋韵戏剧点播网站毕业设计源码112304
    spring boot社区居民健康档案管理系统毕业设计源码220940
    elementui单个输入框回车刷新整个页面
    3ds Max 精模数据优化处理参考
    智慧交通解决方案-最新全套文件
    lua 时间差功能概略
  • 原文地址:https://blog.csdn.net/qq_41980461/article/details/126364932