<template>
  <div :class="anchorLinkClasses">
    <a
      :class="linkTitleClasses"
      :href="href"
      :data-scroll-offset="scrollOffset"
      :data-href="href"
      @click.prevent="goAnchor"
      :title="title"
      >
      {{ title }}
    </a>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "ElAnchorLink",
  inject: ["anchorCom"],
  props: {
    href: String,
    title: String,
    scrollOffset: {
      type: Number,
      default() {
        return this.anchorCom.scrollOffset;
      },
    },
  },
  data() {
    return {
      prefix: "el-anchor-link",
    };
  },
  computed: {
    anchorLinkClasses() {
      return [
        this.prefix,
        this.anchorCom.currentLink === this.href ? `${this.prefix}-active` : "",
      ];
    },
    isActiveA() {
      return this.anchorCom.currentLink === this.href
    },
    linkTitleClasses() {
      return [
        `${this.prefix}-title`,
        this.anchorCom.currentLink === this.href ? `el-anchor-link-a-active` : "",
      ];
    },
  },
  methods: {
    goAnchor() {
      this.anchorCom.currentLink = this.href;
      this.anchorCom.handleHashChange();
      this.anchorCom.handleScrollTo();
      this.anchorCom.$emit("select", this.href);
      const isRoute = this.$router;
      if (isRoute) {
        this.$router.push(this.href, () => {});
      } else {
        window.location.href = this.href;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.anchorCom.init();
    });
  },
};
</script>
