The v-for loop seems to only update the last element instead of all of them, which is incorrect

How can I ensure that all 3 page links in the nav are displayed in 3 languages of user choice? Initially, the language change works fine on page load. However, after clicking on a language change link once, only the last link's language changes instead of all of them. What is causing this issue and how can it be resolved?

app.vue:

<template>
    <nav class="navbar">
        <NuxtLink class="pagelink" :key="page.slug" v-for="page in strings.pages" :href="'/' + page.slug">{{ page.name[lang] }}</NuxtLink>
        <Languages />
    </nav>
</template>
<script>
import Languages from "./components/languages.vue"
import languages from "../services/languages"
export default {
    name: "Navbar",
    data() {
        return {
            open: false,
            strings: {
                pages: [
                    {
                        slug: 'home',
                        name: { az: "Əsas", ru: "Главная", en: "Home" }
                    },
                    {
                        slug: 'about',
                        name: { az: "Haqqımızda", ru: "О нас", en: "About" }
                    },
                    {
                        slug: 'contact',
                        name: { az: "Əlaqə", ru: "Связаться", en: "Contact Us" }
                    }
                ]
            }
        }
    },
    computed: {
        lang() {
            return languages(this)
        }
    }
}
</script>

<style>
* {
    margin: 10px;
}
</style>

languages.vue:

<template>
    <div class="languages">
        <NuxtLink :to="route.path + '?hl=az'">AZ</NuxtLink>
        <NuxtLink :to="route.path + '?hl=ru'">RU</NuxtLink>
        <NuxtLink :to="route.path + '?hl=en'">EN</NuxtLink>
    </div>
</template>

<script>
export default {
    name: "Languages",
    setup() {
        const route = useRoute()
        return {
            route
        }
    }
}
</script>

<style scoped>
div,
div a {
    height: 40px;
    display: inline-block;
}

img {
    height: 60%;
    display: inline-flex;
    margin: 8px;
}
</style>

languages.js:

function languages(page) {
    let langCookie = useCookie("language")
    let language = langCookie.value
    if (page.$route.query.hl) {
        language = page.$route.query.hl
        langCookie.value = language
    }
    return language || 'az';
}

export default languages

Answer №1

The main issue I've noticed in your code is the manipulation of the cookie within the languages function, which is called by your lang computed property.

A computed property should not have side effects, as stated in the Vue documentation.

You should separate the logic and only return the current language or a default value in the computed property.

setup() {
    let langCookie = useCookie('language');

    return {
      langCookie
    }
},

computed: {
    lang() {
        return this.langCookie || 'az';
    }
}

The code to update the language in the cookie should be extracted and only called when needed. For example, you could trigger it when the user clicks on a language link in the selector or use an immediate watcher on the language value from the URL.

<template>
  <div class="languages">
    <!-- Only update the query parameters for the language selection, vue-router will handle the URL computation -->
    <NuxtLink :to="{ query: { hl: 'az' } }">AZ</NuxtLink>
    <NuxtLink :to="{ query: { hl: 'ru' } }">RU</NuxtLink>
    <NuxtLink :to="{ query: { hl: 'en' } }">EN</NuxtLink>
  </div>
</template>

<script>
import { watch } from 'vue';
import { useRoute } from 'vue-router';
import { useCookie } from '?';

export default {
  name: 'Languages',

  setup() {
    const route = useRoute();
    const langCookie = useCookie('language');

    watch(
      () => route.query.hl,
      (newLang) => {
        langCookie.value = newLang;
      },
      {
        immediate: true
      }
    );
  }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Obtain JSON information from a Javascript response using Puppeteer:

While developing a test with Puppeteer and Node, I encountered the need to extract an access token from a response after logging in. Here is the current code snippet: //Click Login Button const loginButton = await page.$(".click-button.dark.ng-star-i ...

I have come across this building error, what do you think is the cause of it?

My attempt to launch my company's React.js project, downloaded from Tortoise SVN, is encountering an issue. PS C:\Projects\Old EHR> yarn start yarn run v1.22.19 $ next start ready - started server on 0.0.0.0:3000, url: http://localhost:30 ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

The state variable is not accurately captured as it passes through various components

For the sake of readability, I have omitted certain sections of my original code. Apologies if this leads to any confusion! In App.js, there is a state variable defined as follows: const [tasks, setTasks] = useState([]) From App.js, the state varia ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

Ways to convert an object with values into an array containing those values

To process the JSON data and convert it into an array with the same values for insertion into my PostgreSQL database using pool.query(message, values), where values should be an array if multiple are present. Currently, my object structure is as follows: { ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

Is there a way to effectively organize an RSS feed using the .isoDate parameter while ensuring that the feed's elements remain interconnected (such as title and link)?

My goal is to organize the RSS feed by the most recent item while ensuring that each title corresponds correctly with its link. Currently, I am parsing and displaying the feed using the .isoDate property, but I am unsure of the best approach to achieve thi ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute ...

Conceal the div element five seconds after the registration process is completed

Is it possible to automatically hide a div 5 seconds after a user registers? Using the timestamp in PHP for the user's registration, there may be a way to achieve this with jQuery, but it's not certain. I found a script online that successfully ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

Guide to generating a downloadable link using React and Express

In my React app, I have a button which is essentially a div. The Button Component returns this structure with all other elements as props: <button className={"button "+styleButton} onClick={handleClick}> {source && <img src= ...

The "Go" button on iPhone triggers an error before the page is sent back

I am facing an issue with a web page that has a form containing multiple submit buttons with different functionalities like clearing the form, performing a calculation, or adding another entry line. The problem arises only on iPhone devices (tested on bot ...

Retrieving information from an object using JavaScript

Hello, I am facing a challenge with extracting data from an object via a web API in ReactJS. It seems like the data returned by the API is not structured properly as a JavaScript object. To view the issue directly in your browser visit: I need assistance ...