Using Vue.js to conditionally render data in a v-for loop

Below is the code snippet I am working with:

<article class="project-card" 
        v-for="item in en.projects" 

Additionally, here are some import statements:

import fr from '../assets/datas/fr.json'
import en from '../assets/datas/en.json'

export default {
  data () {
    return {
      languageActive: 'en',
      en: en,
      fr: fr,

If 'languageActive' is set to 'en', I intend to use 'en.projects' in the v-for loop.

If 'languageActive' is set to 'fr', I intend to use 'fr.projects' in the v-for loop.

However, I have come across information stating that using a v-if with v-for is not advisable.

Any suggestions on how I can achieve this? Thank you!

Answer №1

If you save the languages in an object structure, such as:

data() {
  return {
    langs: { en: en, fr: fr }, // or { en, fr } ;)
    languageActive: 'en',
  }
}

You can access it using a key like this:

<article class="project-card" v-for="item in langs[languageActive].projects" 

Answer №2

To access the en property, make sure to put your languageActive in brackets:

<article class="project-card" v-for="item in [languageActive].projects" 

import fr from '../assets/datas/fr.json'
import en from '../assets/datas/en.json'

export default {
  data () {
    return {
      languageActive: 'en',
      en: en,
      fr: fr,

Answer №3

To implement a ternary operator within a v-for loop, follow this structure:

<div
      v-for="(item, index) in languageActive === 'en' ? en.projects : fr.projects"
      :key="index">
    {{ item }}
</div>

For a straightforward demonstration, refer to this example: https://codesandbox.io/s/quirky-sound-9fksv?file=/src/App.vue

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

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Trying out Vuex mutation and reducers with Vue3 and Vue-test-utils

Currently in the process of transitioning to Vue3, so I ask for understanding in not immediately utilizing Pinia. My reducer is structured like this: export const mutations: MutationTree<UiState> = { SET_LOADING: (state, loading) => { Object ...

Creating dynamic images with animated text using PHP

How can I add a personal touch to my website banners for visitors? 1) Currently, only the first frame of GIF images is being displayed in the animated banners 2) I am looking to incorporate a text field where users can input their desired text. Upon form ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

Running a Chrome content script once an AJAX request has been triggered by the <body> element

I am facing a challenge with running the content script before the DOM is fully loaded. To give context, there is an AJAX request within a tag which gets triggered on $(document).ready(). Once this request is completed, my extension code kicks in. To tra ...

Attempting to store an array of JSON objects in the state, and then utilizing the `map` method to render

I'm just starting out with React. Currently, I'm attempting to store an array of JSON objects in the state and then map those items into the component render. I'm feeling a bit lost on how to debug this as there are no console errors showi ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

Issue with distinguishing JavaScript code from an SVG file

Seeking assistance as I have an SVG file that is mostly composed of a script. My goal is to separate the script for compression purposes, but I am struggling to find a way to achieve this. Any guidance or help on this matter would be greatly appreciated. ...

The React callback is failing to update before navigating to the next page

I'm facing an issue that seems like it can be resolved through the use of async/await, but I am unsure of where to implement it. In my application, there are three components involved. One component acts as a timer and receives a callback from its pa ...

Next.js encountered an issue: React.Children.only function was expecting to receive only one React element child, but received more

I have created a component named Nav located in the components directory. Here is the code for it: import Link from 'next/link'; const Nav = () => { return( <div> <Link href="/"> <a> Home </a> ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

Display a dialogue box when encountering a Vuetify error. Only open the dialogue box under certain conditions

I am currently implementing vuetify into my project. The main issue I am facing is related to the dialog component, which I only want to open in case of an error. The scenario involves a button calling a backend service to save a product in the database, a ...

Can someone please share a straightforward method for dynamically rendering views in Vue.js?

Let's pause and consider the scenario: You're creating a modular interface, where any module that implements it must be able to 'render itself' into the application using a slot and state. How can you achieve this in Vue? An Example S ...