The uniapp global component is used globally (not used in every page template, only supports H5), and the global component method is called functionally

 The easiest way to use it is to write the following code in main.js to display the xxx component on each page

// main.js

// 引入组件
import xxx from "@/components/xxx.vue";

// 将该组件挂载在document.body下
document.body.appendChild(new xxx().$mount().$el);

Functionally call global component methods

Scenario, some  toast  components need to be used as follows

<template>
    <toast ref="toast"></toast>
</template>

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

After transformation, the final usage method is:

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

Method to realize:

1. Create a new render.js in the utils directory

2. Bind render.js to this under main.js

// ...

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

// ...

3. Bind the component to the global in 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. Finally, we can directly call component methods and set component properties in a functional way

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

// 此duration属性在toast组件的data中
this.$r.toast().duration;

Hey, I hope your code will never have bugs and your life will never have ups and downs!

Hey, I hope your code will never have bugs and your life will never have ups and downs!

Hey, I hope your code will never have bugs and your life will never have ups and downs!

Hey, I hope your code will never have bugs and your life will never have ups and downs!

Hey, I hope your code will never have bugs and your life will never have ups and downs!

Hey, I hope your code will never have bugs and your life will never have ups and downs!

 

Advertisement: (provides learning opportunities)

       Front-end exchange learning group: 1063233592

       PHP learning exchange group: 901759097

       WeChat group for front-end and back-end learning and communication: add me on WeChat, fill in the verification message (front-end), and pull you into the group

Guess you like

Origin blog.csdn.net/qq_41980461/article/details/126364932