Vue: 修改数据返回取决于userAgent

问题描述 投票:0回答:1

我是VUE的新手,我尝试着修改了 残疾 值取决于用户代理是否要显示或隐藏支付方式。

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' },
                ]
           }
},

如果用户代理是 菔楝 我试着改变数值。

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

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

javascript vue.js user-agent
1个回答
0
投票

有一个误解,关于什么是 match 返回。如果匹配,则返回一个数组。非匹配字符串. 在失败的情况下,它返回 null. 更多信息 此处.

你可以更新你的代码来解决这个问题。

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

-1
投票

使用 .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的文件中,在 深度反应性 一节中写道:"Vue无法检测到一个数组的以下变化。

Vue无法检测到以下对数组的改变。

1.) 当你直接设置一个带有索引的项目时,例如:vm. items[indexOfItem] = newValue。

2.) 当你修改数组的长度时,例如: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);
© www.soinside.com 2019 - 2024. All rights reserved.