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.