Home » vue » How can I pass hrefs to my method in Vue js with `@click`?

How can I pass hrefs to my method in Vue js with `@click`?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am following the accepted answer of this question: Hide links from Google via JavaScript

I want to pass the href to my method linkAction(), how can I achieve this with an @click?

This is what I have so far

<template>
    <span
      href="https://www.w3schools.com/" <-- some url
      @click="linkAction(this)"
    >
      Link to W3 Schools 
    </span>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class MainContent extends Vue {
  linkAction(e: any): any {
    console.log(e);
  }
}

</script>

I am getting on my console: null. Would appreciate some help. Thanks!

Answers:

In the template you need to change @click="linkAction(this)" to @click="linkAction($event)".

And in method linkAction you do something like this:

linkAction(e) {
  console.log(e.target.getAttribute('href'));
}

###

this is not accessible from template

but you can simply use ref attribute and then use this.$refs to get element

<template>
    <span
      ref="link"
      href="https://www.w3schools.com/" <-- some url
      @click="linkAction"
    >
      Link to W3 Schools 
    </span>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class MainContent extends Vue {
  linkAction(): any {
    console.log(this.$refs.link);
  }
}

</script>

###

One option is to make link as part of your component’s data, and then use it in the linkAction method.

<template>
    <span
      :href="link" 
      @click="linkAction">
      Link to W3 Schools 
    </span>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class MainContent extends Vue {
  data(): any {
     return {
        link: 'https://www.w3schools.com/'
     }
  },

  linkAction(): any {
    console.log(this.link);
  }
}

</script>