Update article translation dynamically in Vue without needing to refresh the page

ArticleController

public function index()
    {
        $locale = Lang::locale();
        // $locale =   Lang::getLocale();
        $articles = Article::withTranslations($locale)->get();
        return $articles;
    }

resources/assets/js/pages/articles/Index.vue

<template>
    <div>
      <div v-for="article in articles" :key="article.articles">
          <div v-for="translation in article.translations">
              <h4>{{ translation.title }}</h4>
              {{ translation.subtitle }}
              {{ translation.content }}
          </div>
      </div>
    </div>
</template>

<script>
import axios from 'axios'

    export default {
        layout: 'basic',

        data: function () {
            return {
                articles: []
            }
        },
        mounted() {
            var app = this;
            axios.get('/api/articles')
                .then(response => {
                  // JSON responses are automatically parsed.
                  this.articles = response.data
                })
                .catch(e => {
                  this.errors.push(e)
                })
        }
    }
</script>

This code snippet is used to display articles based on the detected language in Vue. However, there seems to be an issue when switching languages - the article does not automatically translate. A manual page reload is required for the new language to take effect. How can we implement a solution in Vue to change the language without refreshing the entire page?

Answer №1

It seems like there may be some confusion, but...

So essentially, you're looking to update the article text based on the user's language preference, but you're not currently passing a language parameter to the controller or capturing any language parameters.
One way you could approach this is by implementing something similar to the following:

ArticleController

public function index($locale) // You may need to adjust your route or utilize Request $request; in which case $locale = $request->locale
{
    $articles = Article::withTranslations($locale)->get();
    return $articles;
}

resources/assets/js/pages/articles/Index.vue

<template>
    <div>
        Select Your Language
        <select v-model="language"> 
            <option @click="changeLang('english')">English</option>
            <option @click="changeLang('spanish')">Spanish</option>
            <option @click="changeLang('italian')">Italian</option>
        </select>
    </div>
</template>
<script>
    import axios from 'axios'

        export default {
            layout: 'basic',

            data: function () {
                return {
                    articles: [],
                    language: 'english'
                }
            },
            mounted() {
                this.getArticles ()
            },
            methods: {
                changeLang (lang) {
                    this.language = lang
                    this.getArticles ()
                },
                getArticles () {
                    var app = this;
                    axios.get('/api/articles', {locale: this.language})
                        .then(response => {
                        this.articles = response.data
                        })
                        .catch(e => {
                        this.errors.push(e)
                        })
                }
            }
        }
</script>

I trust that this guidance will assist you effectively.

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

Is it necessary for me to use a .jsx extension when saving my React component files?

After working with React for a few months, I recently noticed that some of my files have the .js extension while others have the .jsx extension. Surprisingly, when I write JSX code in the .js files, everything still functions correctly. Is there any signif ...

What is the best method for adding a JSON array with objects to an already existing table?

After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when t ...

Customizing the font color and size of the MUI DatePicker default textfield is not supported

I'm encountering an issue with the MUI DatePicker as I am unable to customize the font color and font size of the date. Below is my code: const DateSettings = () => { const [value, setValue] = React.useState<Date | null>(); const handleC ...

Enhancing react-input-range with unique Custom Arrow heads

I'm currently working with react-input-range to create a price range slider. While I've managed to customize the CSS of the range slider, I now need to figure out how to add arrow heads inside the circles as shown below: Any guidance on how I ca ...

The issue of event emission not being registered for custom filters in vue-tables-2

I keep encountering this issue: "TypeError: Event.$emit is not a function" every time the watcher triggers. Even though I imported the Event object in my main.js file and can log it to the console, I am using a named prop due to having three different cli ...

The message from Vee-validate indicates that the validator 'required_if' does not exist within the system

I'm currently implementing vee-validate version 3 with Vue 2.7 in my project. Specifically, this is the entry in my package.json file for vee-validate: "vee-validate": "^3.4.5", My issue lies with getting the required_if rule to f ...

The priority of custom attributes in HTML

There seems to be some ambiguity regarding whether data- attributes should be considered primary or secondary syntax. Is there a defined standard for this in major frameworks like Angular? For example, if an attribute is specified as both my-attr and dat ...

Unlock the Power of Typescript: Using the Browser Console to Access Functions

Scenario Within the file ts/app.ts, the following function exists: function foo() { console.log('Hello Word'); } After successful compilation with Webpack, it generates a file named bundle.js. To load this file, use the following script tag ...

What could be causing Vue to remove the style attribute in this particular component?

One issue I encountered with a Vue component is that any style attribute on tags within the component template gets removed from the final output. This occurs in Vue 2.6 without any build step. Interestingly, neighboring components render style attributes ...

The function '.save' is not recognized by Mongoose

As a newcomer, I have been trying to understand the code in this calendar app that I created using express-generator. Everything seems to be working fine with connecting to MongoDB, but I am facing issues when trying to save a document. The section of my ...

The user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

Troubleshooting issue: Event-stream mapSync not functioning properly in async/await scenario

The await commands that I have marked as //******This await does not work */ do not appear to be functioning. It is unclear whether this issue is related to them being in an event stream or if it's a problem with the promise in the imported module. U ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

The self-made <Tab/> element is not functioning properly with the ".Mui-selected" class

I have customized a <Tab/> element and I want to change its selected color using Sandbox demo code export const Tab = styled(MuiTab)({ "&.Mui-selected": { color: "red" } }); However, I've noticed that: 1. Apply ...

Using Reactjs to create a custom content scroller in jQuery with a Reactjs twist

I am attempting to implement the Jquery custom scrollbar plugin here in my React project. Below is a snippet of my code: import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() ...

What is the reason behind the success of chaining $q.when and $q.reject in Angular.js?

Why does this code not trigger the error callback when using $q in Angular.js: $q.when("test") .then($q.reject("error")) .then( function(v) { $scope.result = "Success: " + v; }, function(e) { $scope.result = "Failure: " ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Notify of an Invalid CSRF Token within the Action Buttons Present in the Table

I've encountered a problem with the CSRF token when using a Handlebars each loop. I created a data table using the each loop but I'm unable to submit the delete button. The CSRF token only seems to work for submitting new data (POST) and updating ...

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...