0

我正在根据条件渲染两个文本,并且能够根据条件将方法传递给单击事件。默认文本为 ADD TO COLLECTION,因为最初 hasPaid 属性为 false。付款后,我想将该属性设置为 true

addToCollection函数首先打开一个modal,在modal上,实现handlePayment函数。我已经能够有条件地渲染 div 以使用 v-on="" 显示添加到收藏或下载。我还从 handlePayment 函数返回 hasPaid 属性。

<div class="float-right peexo-faded-text card-inner-text"  :face="face" v-on="!hasPaid ? {click: addToCollection} : {click: handleDownload(face)}">
                                       {{!hasPaid ? 'ADD TO COLLECTION': 'DOWNLOAD' }}
                                    </div>


 data: function () {
            return {
                hasPaid: false,
            }
},
addToCollection(){
                this.showcollectionModal = true;
            },
            handlePayment(){
                this.showcollectionModal = false;
                let accept = true;
                this.showpaymentsuccessmodal = true;
                //this.hasPaid = true;

                return {
                    hasPaid: accept
                }

            },

我希望能够在 handlePayment 函数上设置 hasPaid 属性,以便渲染函数选择它,以便 handleDownload 函数可以工作。

4

1 回答 1

0

这个位的最后一部分将是有问题的:

v-on="!hasPaid ? {click: addToCollection} : {click: handleDownload(face)}"

什么时候hasPaidtrue会立即调用该方法handleDownload。也就是说,它将在渲染期间调用,而不是在<div>单击时调用。

您可以通过将其“包装”在一个函数中来修复它:

{click: () => handleDownload(face)}

我在示例中使用了箭头函数,但如果您愿意,也可以使用普通函数。

就我个人而言,我不会尝试使用v-on.

我的第一直觉是,您应该考虑只使用两个<div>元素并使用v-if来决定显示哪个元素。

如果您确实想使用单个<div>,我会将点击逻辑放在一个方法中。所以:

<div class="..." :face="face" @click="onDivClick(face)">

请注意,尽管与您定义单击侦听器的方式有明显的语法相似性,但这不会立即调用该方法。

然后在组件的方法中:

methods: {
  onDivClick (face) {
    if (this.hasPaid) {
      this.handleDownload(face)
    } else {
      this.addToCollection()
    }
  }
}
于 2019-08-08T13:03:26.690 回答