Keeping an eye on the location and retrieving articles once more - Vuejs

ClassController

<?php

namespace App\Http\Controllers\Classes;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ClassCategory;
use App\Models\Article;
use App\Models\ArticleDescription;
use Lang;

class ClassController extends Controller
{
    /**
     * Display a listing of the resources.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $language = Lang::locale();
        // $language =   Lang::getLocale();
        $articles = Article::withDescriptions($language)->get();
        return $articles;
    }

Class.vue component

<template>
    <div>
      <div v-for="article in articles" :key="article.articles">
          <div v-for="description in article.descriptions">
              <h4>{{ description.title }}</h4>
              {{ description.subtitle }}
              {{ description.content }}
          </div>
      </div>
    </div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
export default {
  layout: 'basic',

  computed: mapGetters({
    language: 'lang/language'
  }),

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

api.php

Route::group(['middleware' => 'guest:api'], function () {
    Route::post('login', 'Auth\LoginController@login');
    Route::post('register', 'Auth\RegisterController@register');
    Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    Route::post('password/reset', 'Auth\ResetPasswordController@reset');

    Route::resource('classes', 'Classes\ClassController');
});

I'm identifying the language on the front end and utilizing it in the controller to retrieve classes for that specific language. This method only functions when I manually refresh the page.

I am utilizing this theme which comes with a navigation bar featuring a language switcher.

How can I monitor changes in language and reload the classes to update the content dynamically without having to refresh the entire page.

Answer №1

<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
  export default {
    layout: 'basic',

    computed: mapGetters({
      locale: 'lang/locale'
    }),

    data: function () {
        return {
            articles: []
        }
    },
    watch: {
      locale: function (newLocale, oldLocale) {
        this.getArticles()
      }
    },
    mounted() {
        console.log(this.locale)
        this.fetchArticles ()
    },
    methods: {
      fetchArticles() {
        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>

Implemented this code and it produced the desired outcome!

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

Experiencing difficulties with loading Facebook wall feed JSON data

Struggling to integrate a Facebook wall feed using jQuery on my website's client side. Utilizing this URL for the Facebook request: Attempted approaches so far: 1. $.getJSON('http://www.facebook.com/feeds/page.php?format=json&id=407963083 ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself. ...

Leveraging Material-UI: Utilize props in useStyles method while employing Array.map()

After delving into the world of passing props to makeStyles in Material-UI, I stumbled upon this insightful answer. The solution presented involves passing props as a variable, which is quite useful. However, my aspiration is to extend this functionality t ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

building CharFields dynamically in Django

I am looking to gather input from the user using CharField. Using the value entered in CharField, I want to generate the same number of CharFields on the same page. For example, if the user enters "3" and clicks OK, it should display "3" CharFields below ...

I have a Key in my component, but it is still searching for a unique key

Just diving into React JS and attempting to transfer data from one component to another using the Link to method I found online... Error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Checking the render method of Videos. Refe ...

Clicking an AngularJS button within a form is causing an unexpected page refresh

I am facing an issue with adding a new input field on click. I have two buttons, one to add and another to remove the input box. When I click on the add button, it should add a set of input boxes, but currently, it only adds one and refreshes the page, dis ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

Integrating a spinner into a React component

I am currently working on implementing a loader for my react component. The idea is that when the background image is loading, it should display 'loading', and once it has finished loading, it should display 'loaded' To test the loader ...

Why is it that only one of these functions can be operational at any given moment?

Even without the if statements, only one of the following will work at a time. To make the first one work, I have to comment out the second. <? if(isset($_POST['region'])){ echo "<script> showRecords('".$_POST['region']." ...

Can you suggest a more "ember-esque" approach to calculate this value?

Note: Due to my current situation, I must work with Ember 2.18 but I am curious if version ^3.4 has certain features that 2.x does not. I am creating a Boolean based on the values of two other Booleans. Within the class, the following code snippet is pres ...

Meteor JS failed to load the CSS file due to an unsupported MIME type

Currently, I am working on a meteor js 1.8 app. I have created a layout and now I want to add CSS to it. Here is the structure I am following: imports -ui --stylesheets --bootstrap.min.css --font-awesome.min.css --skins.css --forms.css All my CSS files ...

Maintain a variable within the scope of _.forEach() that is separate from the array being iterated

Occasionally, I encounter a scenario where objects need to be pushed into a separate array based on the content of a looped array: let customArray: any[]; _.forEach(iteratedArray, (item:any) => { // some irrelevant code... customArray.push(item ...

ng-repeat closing function event

Looking to create a callback method that gets called every time ng-repeat is triggered. After doing some research, I found a couple of options: 1. Using ng-init with ng-repeat This approach involves calling the method using the ng-init property: <ol ...

Can you explain the usage of array literal notation in javascript and provide examples of when it is most effective to

When running JSLint, I encountered the following error message: Issue identified at line 11 character 33: Please use the array literal notation [] instead. var myArray = new Array(); What exactly is the array literal notation and what&apo ...

Typescript error: Unable to instantiate __WEBPACK_IMPORTED_MODULE_1_signature_pad__ as a constructor

Currently, I am working on a project using Angular2 and attempting to incorporate a JS library for signature input from https://github.com/szimek/signature_pad. In my code, I have tried utilizing the library in the following way: // .ts file import * as ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

What's the best approach for implementing TimeInput exclusively in React-Admin?

I discovered this helpful code snippet on the React-Admin documentation that allows me to input both a date and time: import { DateTimeInput } from 'react-admin'; <DateTimeInput source="published_at" /> But now I'm wonderin ...