vue2自定义指令的权限设计(0->1)

2023-11-16 16:38:08 浏览数 (2)

背景

阅读若依前端低代码看见v-permission时去了解vue的directive自定义指令时发现,可注入属性,有点像v-bind的用法。

新建一个vue项目(webpack 模板)

代码语言:javascript复制
# vue init webpack yma16-study
# cd yma16-study
# npm run dev

自定义yma16指令

自定义yma16Auth

代码语言:javascript复制
const yma16Auth = {
  inserted (el, binding, vnode) {
    const { value } = binding
    console.log(binding)
    console.log(el)
    const {visible} = value
    // visible false 移除节点
    if (!visible) {
      console.log('remove', el)
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

在main.js配置

代码语言:javascript复制
const authConfig = {
  isAuthor: true
}
const unAuthConfig = {
  isAuthor: false
}
const yma16Auth = {
  inserted (el, binding, vnode) {
    const { value } = binding
    console.log(binding)
    console.log(el)
    const {visible} = value
    // visible false 移除节点
    if (!visible) {
      console.log('remove', el)
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}
const yma16UnAuth = {
  inserted (el, binding, vnode) {
    const { value } = binding
    console.log('value', value)
    console.log('binding', binding)
    // 未授权 移除节点
    if (!unAuthConfig.isAuthor) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

export {authConfig, yma16Auth, yma16UnAuth, unAuthConfig}

整体的布局设计

代码语言:javascript复制
<template>
  <div class="container">
    <h1>{{ msg }}</h1>
    <el-switch
      v-model="yma16Auth.visible"
      active-text="显示"
      inactive-text="隐藏"
    >
    </el-switch>
      <div>

        <el-button type="primary" @click="reRenderBtn" style="margin:10px 0">
          重新强制渲染
        </el-button>
      </div>
    <div>
       <span style="margin:10px 0">
        授权显示的按钮 v-yma16Auth
      </span>
    </div>
      <div v-if="refreshBtn">
        <el-button v-yma16Auth="yma16Auth" type="primary" :visiable="yma16Auth.visible">
          v-yma16Auth
        </el-button>
      </div>
  </div>
</template>

<script>
export default {
  name: 'Index',
  data () {
    return {
      msg: '自定义指令 directive',
      yma16Auth: {
        visible: true,
        value: false
      },
      refreshBtn: true
    }
  },
  methods: {
    reRenderBtn () {
      // this.$forceUpdate()
      console.log('yma16Auth', this.yma16Auth)
      this.refreshBtn = false
      setTimeout(() => { this.refreshBtn = true }, 500)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

效果

隐藏

显示

结尾

感谢你的阅读!

0 人点赞