gpt4 book ai didi

javascript - VueJS 不响应数组长度的变化?

转载 作者:行者123 更新时间:2023-12-04 17:29:30 28 4
gpt4 key购买 nike

使用单文件模板,我希望有一个按钮,如果数组为空,则显示“单击此处”,如果数组已填充,则显示值。 ajax 工作正常并且对象正在更新,但按钮不会重新呈现。我在这里做错了什么?

<template>
<span>
<button
v-if="value.app_token.length"
class="btn btn-outline-primary btn-sm"
disabled
>Mobile App Token: {{ value.app_token[0].token }}</button>
<button v-else class="btn btn-primary btn-sm" @click="getToken">Click to get Mobile App Token</button>
</span>
</template>

<script>
module.exports = {
props: ["value"],

methods: {
getToken() {
axios
.get("/patients/getToken/" + this.value.id)
.then(response =>
this.value.app_token.splice(
0,
this.value.app_token.length,
response.data
)
)
.catch(error => console.log(error));
}
}
};
</script>

最佳答案

getToken 方法改变了 value 属性,这是不允许的(您可能在控制台中有错误)。

解决方案

为 token 创建一个计算和一个变量来保存获取的数据:

data() {
return {
fetched: null
}
},
computed: {
token() {
let token = JSON.parse(JSON.stringify(this.value.app_token));
if (this.fetched) {
// Now this mutates a copy, not the original
token.splice(0, token.length, this.fetched);
}
return token;
}
}

如果未获取任何内容,则 token 值将与 prop 中的值相同。 否则,它将重新计算为修改后的 token 。更改您的 getToken 方法,使其目的是将数据结果存储在 fetched 中:

methods: {
getToken() {
axios
.get("/patients/getToken/" + this.value.id)
.then(response => this.fetched = response.data)
.catch(error => console.log(error));
}
}

现在在你的 v-if 中使用计算:

v-if="token.length"

并显示为:

{{ token[0].token }}

这是一个demo为你

此外,如果 token prop 本身只是 token 字符串而不是复杂对象的一部分,然后还将 axios id 作为单独的 prop 传递,这将不会那么困惑。

关于javascript - VueJS 不响应数组长度的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61038176/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com