A guide on changing a class dynamically in a Vuejs component by utilizing a variable from Laravel

I have been struggling with this issue and attempted multiple times to find a solution. My goal is to toggle an id using Vuejs based on a boolean value passed from Laravel. I initially achieved this without components, but encountered a problem where updating the id for one button would affect others as well. This led me to consider using a component to solve the issue, but so far I have been unsuccessful.

Below is the code snippet from my blade template within a table loop accessing the $courses variable:

courses.blade:

<form method="POST" action="{{ route('course.completed', $course->name) }}" id="form-submit">
                       {{ csrf_field() }}
    @if ($course->pivot->completed == true)
    <course-buttons id="this.greenClass.aClass">Done</course-buttons>
    @else
    <course-buttons id="this.redClass.aClass">Not Yet</course-buttons>
    @endif
</form>

Snippet from app.js:

require('./bootstrap');
Vue.component('course-buttons', require('./components/course-buttons.vue'))

var vm = new Vue({
el: '#app'
});

And here is the course-buttons.vue file:

<template>

  <button @click.prevent="onSubmit({{ $course }})" type="button" class="btn btn-sm" :id=id><slot></slot></button>

</template>

<script>
  export default {
    props: ['id'],
    data: function() {
      return {
        greenClass: {aClass: 'coursetrue', text: 'Done!'},
        redClass: {aClass: 'coursefalse', text: 'Not Yet!'}
      };
    },
    methods: {
      onSubmit: function(course) {
        axios.post('/MyCourses/' + course.name)
           .then(function (response){
             console.log(response.data.course.pivot.completed)

             if (response.data.course.pivot.completed == true){
               return [
                 vm.redClass.aClass = 'coursetrue',
                 vm.redClass.text = 'Done!',
                 vm.greenClass.aClass = 'coursetrue',
                 vm.greenClass.text = 'Done!'
               ]
             } else {
               return [
                 vm.greenClass.aClass = 'coursefalse',
                 vm.greenClass.text = 'Not Yet',
                 vm.redClass.aClass = 'coursefalse',
                 vm.redClass.text = 'Not Yet'
               ]
             }
           });
     }
    }
  }
</script>

I acknowledge that my code isn't optimal and I have sought help numerous times without success. If you have any insights or suggestions on improving the code to achieve the desired functionality, I am open to learning and making necessary changes.

Currently, I am encountering errors such as "invalid expression" for @click.prevent and "id is not defined" even though I have defined the props and data in the vue component. If you have alternative approaches or solutions to address these issues, I would greatly appreciate your assistance.

Answer №1

One issue that stands out is the need to use v-bind:id here, since you are assigning a Vue variable:

<course-buttons v-bind:id="this.greenClass.aClass">Done</course-buttons>

Another mistake is in the onSubmit method - you do not need to return anything. In addition, you are using vm there when you can simply do the following:

  onSubmit: function(course) {
    axios.post('/MyCourses/' + course.name)
       .then((response) => {
         console.log(response.data.course.pivot.completed)
         if (response.data.course.pivot.completed == true){
             this.redClass.aClass = 'coursetrue',
             this.redClass.text = 'Done!',
             this.greenClass.aClass = 'coursetrue',
             this.greenClass.text = 'Done!'
         } else {
             this.greenClass.aClass = 'coursefalse',
             this.greenClass.text = 'Not Yet',
             this.redClass.aClass = 'coursefalse',
             this.redClass.text = 'Not Yet'
         }
       });
 }

In addition, arrow syntax has been used here. You can find more information on this here.

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

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

Develop a dynamic daily messaging system

I'm interested in incorporating a daily changing message feature on my website. My plan is to store all the messages in a MySQL database and have them displayed daily. Any guidance on how to achieve this would be highly appreciated! Thank you, I ha ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Learn how to display separate paragraphs upon clicking a specific item

New to coding and eager to learn, I have recently started exploring HTML, CSS, and basic JavaScript. In my journey to enhance my skills, I am working on building a website for practice. One particular page of the site showcases various articles, each acc ...

Issues with Weglot link hooks not functioning properly within the sticky header

I have integrated Weglot for translations on my website, aigle.ca. Due to issues with their widget, I am using link hooks instead. You can find more information about link hooks at: weglot.com link-hooks However, when scrolling down the page and the menu ...

Dynamically obtaining the content of a tag using jQuery

Although this question may have been asked multiple times before, I am encountering a peculiar issue. Let me explain the scenario: Within this tag, there is a dynamically loaded integer: <i id="my_id">{{integer value}}</i> I am attempting t ...

Preventing access to drives and desktop until the mandatory HTML form is completed

Looking to develop a webpage in JSP that will automatically open whenever my system is started. Users will be required to fill out a form on this page before proceeding further. If they attempt to bypass filling out the form, they should not have access ...

JavaScript: Implementing a seamless spinning effect for an image [Compass needle]

I have been working on developing a compass app for mobile devices and have successfully created a function that returns the change-values for the compass-needle rotation (e.g. 20). However, I have noticed that setting the 'image-transform' to &a ...

How to turn off code splitting (chunks) in Vue.js and Vite.js

Is there a way to turn off chunking in Vue.js and Vite.js when building a project using Rollup.js? I attempted the following approach, but it did not work for me: export default defineConfig({ build: { rollupOptions: { output: { ...

Avoiding bootstrap modal from disappearing upon validation failure when submit button is pressed using PHP

Could somebody please help me figure out how to prevent a modal from closing when the user clicks the sign-up button under two different scenarios: If the input fields contain invalid data, I want to display a PHP error message If the inputs are valid, I ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

How to Handle Laravel Routing with URL Query Parameters

I am working on a route called stats. This is how my current routing setup looks like: Route::get('stats', 'StatsController@index'); Route::get('stats/{query}', 'StatsController@store'); The main objective is to di ...

Guide on scheduling a daily API GET request in a Node.js script for 11:00pm

I am working on a node js application that involves making an AWS API GET call. http://localhost:3000/amazon/api Within this call, I have specified the necessary functionalities. My goal is to automate this call to run everyday at 11:00PM using node js ...

If an ng-repeat button is constantly changing at a rate of 10 times per second, it may render it unresponsive to clicks

Description On a web page, there is a section displaying the names and scores of different teams. Each team has two buttons (one to decrease score by 1, and one to increase score by 1). The teams are shown using an array and ng-repeat. <!-- Teams Inf ...

Determining the overall cost of products by quantity in Reactjs: A step-by-step guide

Currently, I am immersed in developing an ecommerce site using React and Firebase Firestore to enhance my skills. However, I have encountered a challenging problem recently. I have a component called IndividualCartProducts, which is the output of a map fun ...

Automate table column width adjustments in HTML using Selenium WebDriver

As of now, I am working on automating the process of increasing the width of an HTML table column using Selenium WebDriver. I discovered that I can retrieve the coordinates of x and y by using findElement(By.cssSelector("<Css locator>").getLocation( ...

Creating a mobile-friendly navigation bar with Vuetify for optimal responsiveness

I am attempting to utilize a vuetify tab component as my navigation menu in order to create a responsive navbar using vuetify. The goal is to have a normal navbar that functions like usual, but when viewed on a mobile device, it should hide the menu and di ...

Error encountered when attempting to display a particular user with a specific _id in MongoDB, Node, and React: Failed to convert value "undefined" to ObjectId in the "user" model

I am experiencing an issue on my page where multiple users are displayed. Whenever I click on a user, it should redirect me to their individual page, but instead, I encounter the following error: Cast to ObjectId failed for value "undefined" at path "_id" ...

I could use some assistance with implementing a remainder operator by incorporating it into an if statement and outputting the result to

let userInput = prompt('Please enter a number'); let userNumber = parseInt(userInput); let remainder = userNumber % 18; if (userNumber > 18) { console.log('You are old enough to drive!'); } else if (userNumber < 18 && userN ...

Navigating the Next.js App Router: Leveraging Global Providers

When working with the classic Pages Router of Next.js, you have the option to incorporate a global provider in your _app.js file and wrap it around the entire component tree. This approach ensures that the provider is accessible to all components within th ...