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

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

Enabling auto-expansion for textareas with every keystroke

Currently, I have implemented the following script: jQuery.each(jQuery('textarea[data-autoresize]'), function() { var offset = this.offsetHeight - this.clientHeight; var resizeTextarea = function(el) { jQuery(el).css('h ...

The image will only display upon receiving a link, not a path

Having some trouble displaying an image on my website, despite having successfully done so in the past for other projects. The image is located in the same folder as my HTML file. Here's what I've tried: <img src="reddit.png"/> <img s ...

Vue.js navigation guards, restrict access to all unauthorized routes, grant entry to specific routes upon successful authentication

I'm currently working on implementing a navigation guard in Vue.js with a specific logic: I want to restrict access to all routes that require authentication and redirect users to the login page if they are not authenticated. The only exception is the ...

How do I retrieve the download URL for the file created using Python in my Heroku App?

After developing my Flask App, I uploaded several files to the Heroku filesystem. I'm aware that these files are removed every time the dyno restarts. Now, in my HTML/JavaScript frontend, I'd like to provide users with a download button for thes ...

Just starting out with JS/jQuery and having trouble hiding a div as I thought it should (or revealing it incorrectly)

The issue can be observed by visiting . Upon clicking on a location name, a home "button" appears in the bottom left corner. Clicking this home button is supposed to revert back to the original page layout and hide the button. However, as soon as the curso ...

Having difficulty showing custom events on angular full calendar

After pushing events loaded from the server, I am encountering an issue where they are not being displayed on the calendar. Interestingly, the events are in the correct format and can be seen when printed on the page, but for some reason, they do not show ...

The MeshBasicMaterial in THREE.js successfully renders, while the MeshLambertMaterial does not produce the desired outcome

In my current project, I've been working on creating a randomized sheet composed of arrays containing x, y, and z coordinates to draw triangles between points. You can see the outcome by clicking on this screenshot. Initially, I utilized MeshBasicMat ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

Cleaning up unwanted objects in THREE.js webGL

Our app utilizes THREE.js to showcase 3D body meshes. We have a special object named MeshViewer that manages the rendering process; within the initialize method, we establish this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBu ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

Send reference to parent directly without using a proxy

In my child vue component, there is a referenced object that I emit to the parent like this: const skuForm = ref({ sku: '', oneTime: false, noDiscount: false, korean: false }); const addSku = () => { emit('add', ...

Seeking a way to keep the returned Ajax string consistent and prevent it from fading away after page transition

I have a form that appears when the user clicks on the "Edit" link, allowing them to input their profile information. Upon submission, the data is processed via Ajax and saved in an SQL database using a PHP script. After saving the new profile, I would lik ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Inject a directive attribute dynamically into an element using another directive, and ensure the initial directive is set to 'active.'

Let me explain in more detail. I am utilizing the tooltip directive from the UI Bootstrap suite, which allows me to attach a tooltip to an input element like this: <input type="text" ng-model="inputModel" class="form-control" placeholder=" ...