I have been working on implementing a currency switcher feature. I am trying to call a method when clicking the link and once the method is successfully executed, I want it to reload automatically. However, the automatic reload functionality does not seem to be working. The currency gets stored in a cookie, and refreshing the page manually updates it in the navbar as expected. But ideally, I would like it to reload automatically once the method completes.
Here is the code snippet from the navbar:
<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>
This is the method being used:
methods: {
setCurrency(newcurrency) {
this.$cookies.set(`usercurrency`, newcurrency, {
path: '/',
maxAge: 60 * 60 * 24 * 7
})
// window.location.href = '/'
}
}
I initially considered using window.location.href = '/'
after setting the cookie, but encountered issues because the same method is used in the created hook to set the currency based on the user's country, resulting in a "window not defined" error. Here is the related code snippet:
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
// more cases...
default:
CurrencyParam = 'USD'
}
this.setCurrency(CurrencyParam)
})
.catch((error) => {
console.log(error)
this.setCurrency('USD')
})
}
}
},