【问题标题】:How can I pass hrefs to my method in Vue js with `@click`?如何使用`@click`将hrefs传递给Vue js中的方法?
【发布时间】:2020-01-22 13:30:51
【问题描述】:

我正在关注这个问题的公认答案:Hide links from Google via JavaScript

我想将 href 传递给我的方法 linkAction(),如何使用 @click 实现此目的?

这是我目前所拥有的

<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>

我正在使用我的控制台:null。将不胜感激一些帮助。谢谢!

【问题讨论】:

  • 所以点击时可以在控制台中看到'null'?所以点击处理程序被操纵了,我猜'this'不是'模板'中的已知关键字 - 如果你这样做,@click =“linkAction” - 我想你可能会得到'this'在“e”变量中免费
  • 无需硬编码,无需使用引用:只需通过函数内的事件目标访问它

标签: javascript vue.js vuejs2 nuxt.js


【解决方案1】:

您需要在模板中将@click="linkAction(this)" 更改为@click="linkAction($event)"

linkAction 方法中,你可以这样做:

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

【讨论】:

    【解决方案2】:

    this 无法从模板访问

    但您可以简单地使用ref 属性,然后使用this.$refs 获取元素

    <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>
    

    【讨论】:

      【解决方案3】:

      一种选择是将link 作为组件data 的一部分,然后在linkAction 方法中使用它。

      <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>
      

      【讨论】:

        猜你喜欢
        • 2020-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-21
        • 2019-08-06
        • 2020-04-06
        • 1970-01-01
        • 2017-09-17
        相关资源
        最近更新 更多