Attempting to decode the string prior to selecting an item from the Vue.js/Nuxt array

Hey there, I really appreciate anyone who can assist me with this. I've been dabbling in Laravel for a few months and now I'm trying to dive into studying Nuxt. The specific type of translation I need help with is proving to be quite challenging to find information on.

What I'm attempting to do is populate an array with objects, each object containing the same string in three different languages. I have a function that properly returns the object's string, but I'm unsure about how to specify the locale for my function. This is part of my learning process, and despite searching extensively online, I haven't found much guidance. While I already understand how to perform translations using a locales file, I want to create this structure so that eventually I can retrieve information from an API.

At the moment, everything seems to be running smoothly as the computed function successfully displays a random item from the array on my screen. However, I am struggling to determine the locale and the result of the translation function before executing the math.random.

This is a snippet of my code:

LoadingBar.vue

<template lang="html">
  <div class="loading-page" v-if="loading">
    <h1 class="title">Preparing the ground for you</h1>
    <img src="~/assets/media/photos/agronomy.png" />
    <p class="text">{{tiprandom}}</p>
  </div>

</template>

<script>
import randomtip from '~/components/randomtip.vue'
export default {

layout: 'blank',

components: {
  randomtip
},

      data: () => ({
           loading: true,
           tipolocal_id: 1,
           dicas: [
             {id:1, nome: 'Tip 1: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_en: 'Tip 1: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_es: 'Tip 1: Considere prestarle más atención a las plántulas, ya que son bastante sensibles. Es fundamental mantener la maceta en un área sombreada y siempre controlar el riego.'
                    },
             {id:2, nome: 'Tip 2: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_en: 'Tip 2: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_es: 'Tip 2: Considere prestarle más atención a las plántulas, ya que son bastante sensibles. Es fundamental mantener la maceta en un área sombreada y siempre controlar el riego.'
                    },
             {id:3, nome: 'Tip 3: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_en: 'Tip 3: Consider giving extra attention to the seedlings, as they are quite sensitive. It's crucial to keep the pot in a shaded area and always monitor irrigation',
                    nome_es: 'Tip 3: Considere prestarle más atención a las plántulas, ya que son bastante sensibles. Es fundamental mantener la maceta en un área sombreada y siempre controlar el riego.'
                    },
             ],
    }),
           computed: {
                  tiprandom () {
                    return this.dicas[Math.floor(Math.random()*this.dicas.length)]
                  },
                locale() {
                          if (this.$i18n.locale == 'pt-br') {
                            return 'pt_br'
                          } else {
                            return this.$i18n.locale
                          }
                        }
                      },

    methods: {

            functionDicas(dicas) {
                    if (this.$i18n.locale == 'pt-br') {
                      return dicas.nome
                    } else if (this.$i18n.locale == 'en') {
                      return dicas.nome_en
                    } else if (this.$i18n.locale == 'es') {
                      return dicas.nome_es
                    }
                  },

            
            start () {
               this.loading = true
                    },

            finish () {
              this.loading = false
                    },                    
                    }     
  }
</script>

Answer №1

You may be overcomplicating this task and attempting to solve it in a more complex way when there is a simpler solution available: using nuxt-i18n

Simply put, you can create a file in either json or javascript format containing your translations. Each translation will have a unique key, which you can then reference in your components.

I recommend reading through the provided link 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

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Is it necessary to use the "new" keyword when utilizing JS closure to create objects?

My response to a question about closures on SO included the following code sample: function Constructor() { var privateProperty = 'private'; var privateMethod = function(){ alert('called from public method'); }; ...

Issue with jQuery: Changes are not being triggered and clicks are also not working

I managed to recreate the modifications of my complex script in a simple jsfiddle, which can be found here. Below is the code I am working with locally: HTML <input type="text" id="rangeStart" value="updateMe" /><br/> <input type="text" c ...

VueJS Error: Attempting to access a property that is undefined causing a TypeError (reading 'toLowerCase')

Whenever I attempt to filter and remove items from an array, everything works fine. However, when I try to add new items to the array, I encounter an error message that says "TypeError: Cannot read properties of undefined (reading 'toLowerCase'). ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

Mapping a JavaScript object to an MVC model: A comprehensive guide

I have a JavaScript object as shown below: $scope.docPropIdentityModel = { Owner: {OwnerID:"", OwnerName: ""}, }; I need to send this object to my MVC controller using an AJAX call. Let's say the controller looks like this: controll ...

Inform registered customers by utilizing AngularJS (angular-websocket-service) and Spring Boot to implement Websockets notifications

Exploring the world of AngularJS and FullStack development is an exciting journey for me. The architectural setup of my current app is already in place and ideally should not be altered (for security reasons). I've been able to send messages to the se ...

Enhancing user experience with dynamically resized Jumbotron images based on screen sizes in HTML

I am experiencing an issue with the jumbotron images on my website where they become increasingly zoomed in as the screen size decreases, and are extremely zoomed in on mobile devices. Is this a normal behavior of jumbotrons? I do understand that the image ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Unable to retrieve the unique identifier for this item

When attempting to retrieve the current ID of an item in a table by clicking the Purchase button and using console.dir, it only displays the first element. I have also tried console.dir for this.id but it returns nothing. function listProducts() { ...

a gentle breeze gathers a multitude of entities rather than items

When utilizing a restful server with node.js and sending a collection of entities wrapped in one entity object (Lookups), everything seems to be functioning properly. However, the issue arises when breeze views the entities in the collection as plain objec ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

Utilize a drop-down selector in JavaScript to search and refine the results

Looking for a way to enhance your product search form? Consider adding an option to select a specific shop from the dropdown menu. This will allow users to search for products within a particular store if desired. <form action="#" method="get"> &l ...