Vue: 修改数据 return 取决于 userAgent

Vue: Modify data return depends userAgent

我是 VUE 新手,我尝试修改 disabled 值取决于 userAgent 以显示或隐藏 paymentMethod:

data() {
            return {
                paymentMothods: [
                    { name: 'Visa checkout', img: 'visa.png', disabled: false, height: '19', class: 'v-button' },
                    { name: 'PayPal', img: 'paypal.png', disabled: false, height: '18.9', class: '' },
                    { name: 'PhonePE', img: 'phonepe.png', disabled: true, height: '18.9', class: 'phonepe' },
                ]
           }
},

如果 userAgent 是 phonepe-webview 我尝试更改值:

methods: {
            phopepeMatch: function () {
                let userAgent = navigator.userAgent
                let phonepeMatch = userAgent.match("phonepe-webview")
                if (phonepeMatch === "phonepe-webview"){
                    this.paymentMothods[2].disabled = false
                    return true
                }
                else {
                    return false
                }
            }
},

但这并没有显示付款方式:(

使用.splice().

methods: {
        phopepeMatch: function () {
            let userAgent = navigator.userAgent
            let phonepeMatch = userAgent.match("phonepe-webview")
            if (phonepeMatch === "phonepe-webview"){
                // first you need to copy the whole object
                let payment_method = this.paymentMothods[2];
                // next is to modify the property of the object you want to change
                payment_method.disabled = false;
                // finally, replace the old one with the new object
                this.paymentMothods.splice(2, 1, payment_method);
                return true
            }
            else {
                return false
            }
        }

},

更多信息:

在 Vue 的文档中,在 Reactivity in depth 部分下,它指出:

Vue cannot detect the following changes to an array:

1.) When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

2.) When you modify the length of the array, e.g. vm.items.length = newLength

但是,Vue 确实提供了一种方法,Vue 的反应性系统 将能够检测到您在数组中的更改。

而不是这个:

this.paymentMothods[2].disabled = false

你应该这样做:

let payment_method = this.paymentMothods[2];

payment_method.disabled = false;

this.paymentMothods.splice(2, 1, payment_method);

或者像这样(使用this.$set()):

let payment_method = this.paymentMothods[2];

payment_method.disabled = false;

this.$set(this.paymentMothods, 2, payment_method);

matchreturns的理解有误。如果匹配,它 returns 一个数组, 不是匹配的字符串 。如果失败,它 returns null。更多信息 here.

您可以更新代码来解决此问题:

phopepeMatch: function () {
  let userAgent = navigator.userAgent
  let phonepeMatch = userAgent.match("phonepe-webview")
  if (phonepeMatch === null){
    return false
  }
  else {
    this.paymentMothods[2].disabled = false
    return true
  }
}