【发布时间】:2022-01-07 14:56:18
【问题描述】:
我正在研究货币切换器。我在单击链接时调用方法,在方法成功后希望它重新加载。但重新加载根本不起作用。货币存储在 cookie 中,如果我手动刷新页面,它也会在导航栏中更新,但我希望它在方法完成后自动重新加载。
这是导航栏中的代码..
<b-dropdown position="is-bottom-left" aria-role="menu">
<template #trigger>
<a class="navbar-item font-bold" role="button">
{{currency}}
<b-icon icon="menu-down"></b-icon>
</a>
</template>
<b-dropdown-item v-for="(item, index) in currencies" :key="index" has-link aria-role="menuitem">
<a class="no-underline" @click="setCurrency(item.iso, (reload = true))"><span class="text-pink-600 font-bold">{{item.fullname}} ({{item.iso}})</span></a>
</b-dropdown-item>
</b-dropdown>
这是方法。
methods: {
setCurrency(newcurrency) {
this.$cookies.set(`usercurrency`, newcurrency, {
path: '/',
maxAge: 60 * 60 * 24 * 7
})
// window.location.href = '/'
}
}
我想在设置 cookie 后使用window.location.href = '/',但我不能这样做,因为我在创建的钩子中使用相同的方法,如下面的代码,根据用户国家/地区设置货币,它会说窗口未定义。
created() {
const isCurrency = this.$cookies.get('usercurrency')
const isUserCountry = this.$cookies.get('usercountry')
if (isCurrency === undefined) {
if (isUserCountry === undefined) {
fetch('https://ipinfo.io/json?token=*********')
.then((response) => response.json())
.then((jsonResponse) => {
const country = jsonResponse.country
this.$cookies.set(`usercountry`, country, {
path: '/',
maxAge: 60 * 60 * 24 * 7,
})
var CurrencyParam
switch (country) {
case 'IN':
case 'NP':
CurrencyParam = 'INR'
break
case 'US':
CurrencyParam = 'USD'
break
case 'AU':
CurrencyParam = 'AUD'
break
case 'CA':
CurrencyParam = 'CAD'
break
case 'GB':
CurrencyParam = 'GBP'
break
case 'AE':
CurrencyParam = 'AED'
break
case 'RU':
CurrencyParam = 'RUB'
break
case 'JP':
CurrencyParam = 'JPY'
break
case 'SG':
CurrencyParam = 'SGD'
break
case 'FR':
case 'FI':
case 'DE':
case 'GR':
case 'HU':
case 'IT':
case 'LT':
case 'MT':
case 'NL':
case 'NO':
case 'PL':
case 'PT':
case 'RO':
case 'RS':
case 'ES':
case 'SE':
case 'CH':
case 'UA':
CurrencyParam = 'EUR'
break
default:
CurrencyParam = 'USD'
}
this.setCurrency(CurrencyParam)
})
.catch((error) => {
console.log(error)
this.setCurrency('USD')
})
}
}
},
【问题讨论】:
-
所以你在这里对整个 SPA 进行核弹??
-
可能我的方法在这里完全错误!当我使用 nuxt 时,你能建议一些其他方法来实现这一点吗?我对 vue 和 nuxtjs 很陌生。我很想按照你的想法来实施这个
-
通常,在 Vue(或 Nuxt,在这种情况下也是如此)中,您使用的是响应式状态,并且当您正确触摸它时会更新。在这里,您将对整个 SPA 进行核对,这将在性能方面存在很多问题,并且会破坏所有内容。所以,是的,这是 100% 错误的。我不确定您是如何在您的应用中处理货币的,但您应该仅改变这一货币,而不是破坏页面。至于具体如何,这取决于并且需要相当长的时间才能正确重写。你可能会在谷歌上搜索处理 i18n 的方法,因为它在这里有点相似。
-
为什么不在 JSON 文件或至少一个数组中设置您的货币?你的代码会更干净。
-
@V.Thakur 这会破坏页面,因为您正在重新加载选项卡并破坏 SPA。如果您使用谷歌文章了解 SPA 的工作原理,您会看到 F5 或在 URL 中粘贴并提交会破坏 SPA:您会看到您的页面闪烁为空白。我在谈论 i18n 的实现方式,你可以对货币做同样的事情,但它本身并不是直接的解决方案。
标签: javascript vue.js nuxt.js