vue3 自定义全局

和vue2对比

在这里插入图片描述

具体案例

新建 mixins文件夹

// 自定义插件
import * as directives from "./directives"
import wxjButton from "./components/wxjButton/index.vue"

let show = () => console.log("show")

export default {
    install(app) {
        // 原型绑定 属性或方法
        app.config.globalProperties=show

        // 注册全局指令
        Object.keys(directives).forEach(k => app.directive(k, directives[k]))

        // 注册全局组件
        app.component("wxjButton", wxjButton)

        console.log(app);
    }
}

组件内使用全局变量
import { getCurrentInstance } from "vue";
const currentInstance = getCurrentInstance();
const message = currentInstance?.appContext.config.globalProperties.$message;

main.js中导入

// 导入自定义 plugins
import myPlugins from  "./mixins"
app.use(myPlugins).use(element).use(store).use(router).mount('#app')

directives.js

const color = {
    inserted: function (el, binding, vnode) {
        el.style.color = binding.value
    },
}

// 直接鉴权
let permission = {
    inserted(el, binding) {
        let value = binding.value || 'normal'; // 获取到 v-permission的值
        if (value) {
            let hasPermission = checkArray(value);
            if (!hasPermission) { // 没有权限 移除Dom元素
                el.parentNode && el.parentNode.removeChild(el);
            }
        }
    }
}

function checkArray(key = "normal") {
    let arr = ["normal", "teacher", "admin"]  // 标识 这是一个
    if (arr.includes(key) && key !== "normal") {
        return true // 有权限
    } else {
        return false // 无权限
    }
}

// 和store集合的鉴权
let permissionstore = {
    inserted(el, binding, vnode) {
        // console.log(el)
        // console.log(binding)
        // console.log(vnode)
        if (vnode.context.$store.getters.isHas) { // 没有权限 移除Dom元素
            el.parentNode && el.parentNode.removeChild(el);
        }
    }
}

export {
    permissionstore,
    permission,
    color
}

wxjButton.vue

<template>
    <button  @click="wxj_btn_click" class="wxj_button">
        <slot>Submit</slot>
    </button>
</template>
<script>
export default {
  name: "wxjButton",
  methods: {
    wxj_btn_click(){
        this.$emit("click")
    }
  },
};
</script>
<style lang='less' scoped>
.wxj_button{
    padding: 5px 10px;
    font-size: 16px;
    outline: none;
    border-radius: 3px;
    background-color: turquoise;
    color: #fff;
    border: none;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值