Vue中directives的用法


Vue中directives的用法
關於 vue 中 directives 的用法問題,詳細可以參考vue官方對directives的解釋

當前文章主要講述directives怎么用,directives做權限按鈕的功能

###1. directives 怎么用###
不錯的示例,可以參考下,點擊訪問

directives 在生命周期內用

export default {
    data() {
        return {};
    },
    directives: {
        "local-test": function(el, binding, vnode) {
            /** el可以獲取當前dom節點,並且進行編譯,也可以操作事件 **/
            /** binding指的是一個對象,一般不用 **/
            /** vnode 是 Vue 編譯生成的虛擬節點 **/
            el.style.border = "1px solid red";  //操作style所有樣式
            console.log(el.value);  //獲取v-model的值
            console.log(el.dataset.name);  //data-name綁定的值,需要el.dataset來獲取
            console.log(vnode.context.$route);  //獲取當前路由信息
        }
    },
    components: {},
    filters: {},
    watch: {}
};

###2. directives 做權限按鈕的功能###
directives 在全局main.js中注冊

路由配置:

    path: '/permission',
    component: Layout,
    name: '權限測試',
    meta: { btnPermissions: ['admin', 'supper', 'normal'] },  //頁面需要的權限
    children: [
        {
            path: 'supper',
            component: _import('system/supper'),
            name: '權限測試頁',
            meta: { btnPermissions: ['admin', 'supper'] }  //頁面需要的權限
        },
        {
            path: 'normal',
            component: _import('system/normal'),
            name: '權限測試頁',
            meta: { btnPermissions: ['admin'] }  //頁面需要的權限
        }
    ]


自定義指令:

    import Vue from 'vue'
    /**權限指令**/
    const has = Vue.directive('has', {
            bind: function (el, binding, vnode) {
                 // 獲取按鈕權限
                let btnPermissions = vnode.context.$route.meta.btnPermissions.split(",");
                if (!Vue.prototype.$_has(btnPermissions)) {
                    el.parentNode.removeChild(el);
                }
            }
        });
     // 權限檢查方法
    Vue.prototype.$_has = function (value) {
        let isExist = false;
        let btnPermissionsStr = sessionStorage.getItem("btnPermissions");
        if (btnPermissionsStr == undefined || btnPermissionsStr == null) {
            return false;
        }
        if (value.indexOf(btnPermissionsStr) > -1) {
            isExist = true;
        }
        return isExist;
    };
    export { has }

     /*然后在main.js文件引入文件*/
    import has from './public/js/btnPermissions.js';

    /*頁面中按鈕只需加v-has即可*/
    < el - button @click='editClick' type = "primary" v - has > 編輯</el - button >


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM