0

我的list.vue文件中有以下元素:

<a id="anchorLink"
    class="button is-primary is-fullwidth-mobile mb-sm"
    @click="functionA()">
    <span>Call Function A</span>
</a>

这就是功能functionA

async functionA() {
  // do something
},

我要做的就是禁用锚链接直到functionA处理完成,然后只启用链接。

所以我尝试了所有这些选项来禁用它,但到目前为止没有运气:

选项01:

async functionA() {
document.getElementById('anchorLink').disabled = true;
// do something
}

选项02:使用.prevent

<a id="anchorLink"
    class="button is-primary is-fullwidth-mobile mb-sm"
    @click.prevent="functionA()">
    <span>Call Function A</span>
</a>

选项03:使用v-on:click.prevent

    <a id="anchorLink"
    class="button is-primary is-fullwidth-mobile mb-sm"
    v-on:click.prevent="functionA()">
    <span>Call Function A</span>
</a>

当我尝试所有选项时,我没有收到任何控制台错误,但它仍然无法完成工作。

有人可以帮我吗?

4

2 回答 2

1

考虑到您提供的代码。据我了解您的问题,您可以<a>通过将动态类绑定到类的数据属性(如:class您的anchor标签)来禁用链接。为您的标签使用基于对象的类语法<a>,然后用一个boolean值切换类名。

注意:链接red在禁用阶段会变成颜色,当功能执行完成后会变回原来的颜色。虽然它是红色的,但您将无法执行functionA()

在这里测试

你的 vue 标记

<template>
 <div id="app">
 <a id="anchorLink"
  :class="{ isDisabled: !call }"
  @click="functionA">
  <span>Call Function A</span>
 </a>
 </div> 
</template>

Vue 类

export default {
 name: 'App',
 data: () => ({
   call: true
 }),
 methods: {
  async functionA(){
   if (this.call) {
    this.call = false;
    console.log('running function')
    setTimeout(()=> {
      this.call = true // mimic function execution behaviour using setTimeout here
    }, 2000)
   }
  }
 }
} 

CSS

pointer-events属性定义元素是否对指针事件做出反应。不需要添加,但您可以包含它。

.isDisabled {
  pointer-events: none;
  color: red
}

希望能帮助到你!

于 2020-09-21T12:43:35.373 回答
1

很难具体回答您的 Q(您的代码示例不完整)。

无论如何,这是 +- "hello world"的想法(等待承诺而不是做某事)。

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: () => ({
    terms: true
  }),
  computed: {
    isDisabled: function(){
      return !this.terms;
    }
  },
  methods: {
    async disable_for_2_seconds() {
      try {
        this.terms = !this.terms;
        const msg = await hello_Promise();
        this.terms = !this.terms;
        console.log('Message:', msg);
      } catch(error){
        console.error(error);
      }
    },
  },
})

function hello_Promise() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Function A - Time Ends! Enable button');
    }, 2000);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h3>Async/Await</h3>
  <button :disabled='isDisabled' v-on:click="disable_for_2_seconds">Disable Button for 2 seconds on click</button>
  <br>Disable: <b>{{isDisabled}}</b>
</div>

禁用/启用按钮相关 Stackoverflow Q:how-to-disable-button-in-vuejs

相关 JS 文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

于 2020-09-21T12:55:04.043 回答