<template>
  <span>
    <el-button
      style="width: 100%"
      v-bind="$attrs"
      v-on="$listeners"
      v-if="hasPer && button"
    >
      <slot />
    </el-button>
    <el-link v-bind="$attrs" v-on="$listeners" v-else-if="hasPer">
      <slot />
    </el-link>
  </span>
</template>

<script>
import { mapGetters } from "vuex";
import { loopFunc } from "@/utils/index";
export default {
  name: "PermissionButton",
  inheritAttrs: false,
  props: {
    // 是否是按钮
    button: {
      type: Boolean,
      default: false,
    },
    // 权限code
    perms: {
      type: String,
      default: "",
    },
  },
  computed: {
    ...mapGetters(["allMenus"]),
  },
  data() {
    return {
      hasPer: false,
    };
  },
  watch: {
    perms: {
      handler(value) {
        if (!value) {
          return;
        }
        this.hasPer = this.hasPermission();
      },
      immediate: true,
    },
  },
  methods: {
    hasPermission() {
      const allMenus = this.allMenus;
      let hasPer = false;
      const callback = (item) => {
        if (item.perms && item.perms == this.perms) {
          hasPer = true;
          return;
        }
      };
      loopFunc(allMenus, callback);
      return hasPer;
    },
  },
};
</script>
