Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue

Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with how to handle this.

<template>
  <b-dropdown id="dropdown-buttons" :text="selectedOptionDropdown" class="m-2">
      <template v-for="(item, i) in languages">
        <b-dropdown-item-button class="eslanguage" v-bind:data-lang="item.lang" :key="i" @click="selectedLanguage">{{ item.name }}</b-dropdown-item-button>
    </template>
  </b-dropdown>
</template>

<script>
import i18nService from "@/core/services/i18n.service.js";

export default {
  name: "ESDropdownLanguage",
  data() {
    return {
      languages: i18nService.languages,
      selectedOptionDropdown: ''
    };
  },
  methods: {
    selectedLanguage(e) {
        const el = e.target.closest("eslanguage");
        const lang = el.getAttribute("data-lang");

        i18nService.setActiveLanguage(lang);
    },
    selectedOptionDropdown() {
     // Unsure what to implement here
    }
  },
  computed: {
  }
};
</script>

Another file:

const i18nService = {
  defaultLanguage: "en",

  languages: [
    {
      lang: "en",
      name: "English",
      flag: process.env.BASE_URL + "media/svg/flags/226-united-states.svg"
    },
    {
      lang: "nl",
      name: "Nederlands",
      flag: process.env.BASE_URL + "media/svg/flags/237-netherlands.svg"
    }
  ],

  /**
   * Store the active language in localStorage
   * @param lang
   */
  setActiveLanguage(lang) {
    localStorage.setItem("language", lang);
  },

  /**
   * Retrieve the current active language
   * @returns {string | string}
   */
  getActiveLanguage() {
    return localStorage.getItem("language") || this.defaultLanguage;
  }
};

export default i18nService;

Answer №1

To optimize the dropdown functionality, add v-model and utilize computed properties.

For a practical demonstration, check out this example: Vue SFC Playground

<template>
  <select v-model="language">
      <option :value="item.lang" v-for="(item, i) in languages">
        {{ item.name }}
    </option>
  </select>
</template>

<script>
export default {
  computed: {
    languages() {
      return i18nService.languages
    },
    language: {
      get(){
        return i18nService.getActiveLanguage()
      },
      set(lang){
        i18nService.setActiveLanguage(lang)
      }
    }
  }
};

const i18nService = {
  defaultLanguage: "en",
  languages: [
    {
      lang: "en",
      name: "English",
    },
    {
      lang: "nl",
      name: "Nederlands",
    }
  ],
  setActiveLanguage(lang) {
    localStorage.setItem("language", lang);
  },
  getActiveLanguage() {
    return localStorage.getItem("language") || this.defaultLanguage;
  }
};
</script>

If Bootstrap is needed, consider using b-form-select instead:

Update your language objects to include value and text

<template>
    <b-form-select v-model="language" :options="languages"></b-form-select>
</template>
<script>
export default {
  computed: {
    languages() {
      return i18nService.languages
    },
    language: {
      get(){
        return i18nService.getActiveLanguage()
      },
      set(lang){
        i18nService.setActiveLanguage(lang)
      }
    }
  }
};

const i18nService = {
  defaultLanguage: "en",
  languages: [
    {
      value: "en",
      text: "English",
    },
    {
      value: "nl",
      text: "Nederlands",
    }
  ],
  setActiveLanguage(lang) {
    localStorage.setItem("language", value);
  },
  getActiveLanguage() {
    return localStorage.getItem("language") || this.defaultLanguage;
  }
};
</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

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text, < ...

Issue with alert not being triggered in browser when using HTML and JavaScript function

Just starting out with HTML and Javascript! I'm working on a simple program where users can input a card number, and the browser should indicate whether it is valid (between 13-16 digits) or not. The website looks great, but I'm not getting an ...

Obtain a Calculated Result from a Loop in Vue

I am currently working on a project where I need to check which checkboxes are ticked in different categories so that I can display the total number of checked items next to each category name. I have come up with a code that loops through the selected ite ...

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

Design a clear button for MUI autocomplete feature

I'm currently working on a project where I need to implement a button that clears the MUI autocomplete value and removes the data from the UI. Although I've managed to delete the data from the UI with the code provided, the onChange value remain ...

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

Error in TypeScript - Anticipated 1-2 arguments, received either none or multiple. Code Issue TS2556

While working in JavaScript, I had no issues with this code snippet. However, when I attempted to implement it in a TypeScript Project, an error surfaced. The problem seems to revolve around the fetch(...args) function call. const fetcher = (...args) =&g ...

Error message: "An issue occurred with the Bootstrap Modal in

I've designed an AngularJS app like so: <!DOCTYPE html> <html ng-app="StudentProgram"> <head> <title>Manage Student Programs</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2. ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

The v-tabs component in Vuetify seems to be unable to fill 100% of the available

When using the v-tabs component, I noticed that it doesn't take up 100% of the height. Upon further inspection, I found that all the tab items (tab contents) are wrapped inside a <div class='v-tab__items'> your content </div ...

Steps to extract a hash from a document's URL

The following code is used: jQuery(document).ready(function() { console.log($(this)); }); After running this code, the object displayed in the console is: [Document mypage.html#weather] How can I retrieve the last ID from this object? In this ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

Having trouble with the express-stormpath login feature for users who have authenticated with their email?

As I run a basic node.js/Express server with express-stormpath for user authentication, everything runs smoothly without email verification. However, email verification is essential for various reasons; nevertheless, my email-verified users face issues whi ...

Connecting an admin dashboard to a MERN e-commerce application: A step-by-step guide

In the process of developing an e-commerce platform, I find myself using React.js for the frontend and Node.js/Express.js for the backend. My current challenge lies in creating a seamless dashboard to manage items within the app. One possible solution wo ...