Vue. A variable that changes dynamically in v-if conditions

How can I include a variable in a v-if statement based on my specific situation? I have a data variable called language = 'en' and a large json object with data in multiple languages (referred to as message). Here is an example of the structure of the message json:

"message": {
  "en": 1,
  "es": 2
}

I would like the code to look something like this:

<span v-if="message.lang">some data</span>

When written like this, it functions properly:

<span v-if="message.en">some data</span>

However, when attempting to use a variable like so:

<span v-if="message[lang]">some data</span>

The above approach does not work as expected, preventing the use of the lang variable. Is there anyone who can assist me with this issue?

Answer №1

Instead of modifying your message object directly, you can utilize the lang property as a computed property that points to a specified property currentLang="en" in your data. This allows you to dynamically update the language property without changing the original message object. Here's an example:

 data: {
        currentLang: 'en',
        ...
      }

When the corresponding button is clicked, invoke a method like this:

onLangChange(event){
this.currentLang = "es";
}

Any change to currentLang will trigger the computed function for lang:

 computed: {
    lang: function () {
      return this.currentLang;
    }
  }

This will automatically reflect the changes in the HTML:

 <span v-if="message[lang]">some data</span>

Answer №2

Have you set the lang property in your data properly?

<template>
  <h1>{{ message[lang] }}</h1>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      lang: 'en',
      message: {
        en: 'foo bar',
        fr: 'machin truc'
      }
    }
  }
};
</script>

You might want to explore https://github.com/kazupon/vue-i18n for further clarification.

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

Limiting the number of times a specific character appears using a regular expression

Currently, I am in search of a regular expression that allows me to set a limit on the number of times a special character can appear. For instance, if I want to restrict the occurrence of * to a maximum of 5 times in the entire text, then the output shou ...

Issue with Electron | JavaScript Runtime

Attempting to utilize WebTorrent with Electron and Node.js for torrent downloading. Here is the code snippet in main.js: const electron = require('electron') const { app, BrowserWindow } = electron const path = require('path') const u ...

Error message: "jQuery Ajax CORS request returning undefined value"

I am delving into the world of cross-domain Ajax requests for the first time by interacting with an API. Utilizing jQuery, I aim to extract specific elements from the response and display them on the webpage. Here is the code snippet for the request: $.a ...

Steer clear of downloading images while on your smartphone

As I develop a responsive website, I encounter the challenge of optimizing image loading based on viewport size. While using CSS to hide images not needed for certain viewports can reduce display clutter, it does not prevent those images from being downloa ...

Don't forget to retain filled values when navigating with Vue Router

I have a quick and straightforward question that I would appreciate your input on. In my Vue router setup, I have added navigation tabs for "Home" and "Configuration." On the "Configuration" page, I input some data without saving it, then navigate back t ...

"Utilizing Bootstrap Tour for Easy Navigation: Automatically Scroll Back to the Top with

I have a Bootstrap tour set up with code that is meant to capture the user pressing the end tour button and scroll them back to the top of the screen. However, currently the code runs when a new popover loads instead of when the end tour button is clicke ...

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Determine the number of entries in a JSON object

I am encountering an issue while trying to calculate the number of records in a JSON object, as I am getting an incorrect count. Snippet var jsonObject = {"d":"[{\"Country\":\"\",\"CountryCo ...

Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

A Vue.js component containing a decimal variable within its data

When working with data in a Vue.js component, the decimal type is not included among the possible types (String, Number, Boolean, Array, Object, Date, Function, Symbol). How can we define a variable of this type? ...

Trouble arises when trying to define the style for an element generated through the Document

I'm having trouble setting the style for a 'tr' element created using DOM within JavaScript. Here's the code snippet: var tr = document.createElement("tr"); tr.onmouseover=function(){this.style.backgroundColor='#fbf9e0';}; ...

Error message notifying user that an index is not defined in an ajax

This may appear to be a repetitive question, but I assure you it's not. Despite my efforts on Google, the bug persists. The problem lies in the php script's inability to set the $_POST array to the value passed by the ajax post request. I have a ...

"Enhancing user interaction with Vue.js through the stunning ripple effect on

Is there a way to customize the ripple effect from this source so that it doesn't always have to be a DIV? Here's an example: Currently, when I implement it like this: <ripple class="btn">send</ripple> It works as expected, but as ...

Utilizing the power of AngularJS in conjunction with the Edmunds Media API to retrieve stunning

Scenario: Utilizing a Rails application and $http.get in AngularJS to retrieve photos from the Edmunds.com MEDIA API. GOAL: To use ng-repeat to cycle through the vehicle photos. ISSUE: While I am able to successfully fetch a single image, I am struggling ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...