1

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!

AlyssaAlex
  • 696
  • 2
  • 9
  • 33
  • so you can see 'null' in the console when you click? So the click handler is rigged up, I'm guessing that 'this' isn't a known keyword in the 'template' - if you just do, @click="linkAction" - I think you might get the 'this' for free in the 'e' var – Kyle Jan 22 '20 at 13:36
  • No need to hard-code it, no need to use ref's: just access it via the event target inside your function – Dexygen Jan 22 '20 at 13:41

3 Answers3

2

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'));
}
drijan
  • 56
  • 4
1

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>
farincz
  • 4,943
  • 1
  • 28
  • 38
-1

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>
Suresh
  • 4,091
  • 28
  • 35