I am building a Laravel app and trying to use vue.js (without much success!). I'm not understanding the way components work with ajax data. Almost all examples I've found showing this functionality define the data for the component at the app level, not the component level.
I'm trying to dynamically define my data in the component itself, and always get the error that Property or method tasks is not defined on the instance but referenced during render. Here's the component, which is meant to just call out to an endpoint to pull basic "to do" tasks:
Vue.component('tasks', {
data: function() {
return {
tasks: []
}
},
mounted() {
this.getTasks();
},
methods: {
getTasks() {
axios.get('/tasks').then(function (response) {
this.tasks = response.data;
console.dir(this.tasks);
})
.catch(function (error) {
console.log(error);
});
}
},
template: `
<div class="card">
<div class="card-title">{{ task.name }}</div>
<div class="card-body">
<div class="service-desc">{{ task.description }}</div>
<div class="task-notes"><input class="form-control" v-model="task.notes" placeholder="Notes"></div>
<div class="task-active"><input type="checkbox" checked data-toggle="toggle" data-size="sm" v-model="task.active" v-on:click="$emit('disable')"></div>
</div>
</div>
`
});
the component is called from within the blade template using:
<tasks v-for="task in tasks" :key="task.id"></tasks>
tasks is declared in the data function, so I'm not sure why vue is telling me it's not defined?
When you define a data property on a component it's only available within that component and its template. Your v-for directive is in the parent scope (i.e outside of the component where tasks is defined).
The simplest solution here is probably to move the container element inside the component, and iterate over the tasks there:
<div>
<div class="card" v-for="task in tasks" :key="task.id">
<div class="card-title">{{ task.name }}</div>
<div class="card-body">
<div class="service-desc">{{ task.description }}</div>
<div class="task-notes"><input class="form-control" v-model="task.notes" placeholder="Notes"></div>
<div class="task-active"><input type="checkbox" checked data-toggle="toggle" data-size="sm" v-model="task.active" v-on:click="$emit('disable')"></div>
</div>
</div>
</div>
Note: you can't use v-for a template's root element, which is why you'd move the container element into the template.
An alternative is break this into two components (e.g. TaskList and TaskItem) where the parent component is responsible for fetching the tasks from the API. The child component can just receive a single task as a prop and render it to the UI.
TaskList
Vue.component('task-list', {
data: function() {
return {
tasks: []
}
},
mounted() {
this.getTasks();
},
methods: {
getTasks() {
axios.get('/tasks').then(response => {
this.tasks = response.data;
console.dir(this.tasks);
})
.catch(error => {
console.log(error);
});
}
},
template: `
<div class="container">
<task-item
v-for="task in tasks"
:key="task.id"
:task="task"
/>
</div>
`
});
TaskItem
Vue.component('tasks', {
props: {
task: {
required: true
}
},
template: `
<div class="card">
<div class="card-title">{{ task.name }}</div>
<div class="card-body">
<div class="service-desc">{{ task.description }}</div>
<div class="task-notes"><input class="form-control" v-model="task.notes" placeholder="Notes"></div>
<div class="task-active"><input type="checkbox" checked data-toggle="toggle" data-size="sm" v-model="task.active" v-on:click="$emit('disable')"></div>
</div>
</div>
`
});
The advantage of this is that it separates the responsibility of the components a little better. You could add logic to the TaskList component to handle displaying a loading spinner and/or error messages for the API call, while TaskItem only has to concern itself with displaying a single task.
Related
Sorry for the next question, Im really new on VUE.
I have a button on my blade, when I do it click I want to retrieve the info of the customer depend of the ID that get on my controller, I get the ID #3 and I click on CUSTOMER INFO Button, I want to see the info of this customer from the database
This is my function on my Controller CustomersController.php
public function showcustomers($idcustomer)
{
$Customers = Customers::find($idcustomer);
return view('showcustomer',
['Customers' => $Customers]);
}
And this is my button on Blade showcustomer.blade.php :
<div id="cita">
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-xs-6">
<button v-on:click="showinfo = !showinfo" type="button" class="w3-btn w3-blue" style="width:100%">CUSTOMER INFO</button>
</div>
</div>
</div>
</div>
<br/><br/>
<div class="container align-content-between">
<div class="row text-center">
<div class="col-md-12 col-xl-12">
<information v-if="!showinfo"></information>
</div>
</div>
</div>
</div>
My app.js
Vue.component('information', require('./components/information.vue').default);
var app = new Vue({
el: '#cita',
data: {
showinfo: true,
}
});
And finally my information.vue
<template>
<div id="information">
<h4>Information {{ Customers.name }}</h4>
</div>
</template>
<script>
export default {
name: "information"
}
</script>
<style scoped>
</style>
Standard way of doing that is you will be implementing an ajax request where your front-end or Vue will fetch the necessary information from back-end via ajax request.
Another way of achieving that is you will be using properties or attributes in VUE
from your information.vue add a props maybe customerName or orderId or both
<template>
<div id="information">
<h4>Information {{ customerName }}</h4>
<h4>ID {{ orderID }}</h4>
</div>
</template>
<script>
export default {
props:["customerName","orderID"],
name: "information"
}
</script>
<style scoped>
</style>
in you showcustomer.blade.php you can pass the data from php to your vue by adding attributes based on the property name declared on you vue template
<information customer-name="John Mahu" order-id="0099812-ABC" v-if="!showinfo"></information>
or populate from your PHP variable
<information customer-name="{{ $Customers->customer_name }}" order-id="{$Customers->some_order_id}" v-if="!showinfo"></information>
Read more about vue props
https://v2.vuejs.org/v2/guide/components-props.html
I have a special problem.
I am making an Ajax request to get data from the db without updating.
The response I get should be outputted in a advanced way like this:
#foreach ($tasks as $task)
<div class="pr-1">
<div onclick="openComponent('modal-task', {{ $task->id }});setGlobalIndex({{ $task->id }});" title="{{ $task->title }}" class="calendar-task hover:opacity-75 cursor-pointer" style="background-color: #{{ $task->color }};">#{{ $task->id }} {{ ucfirst(substr($task->title, 0, 23)) }}</div>
</div>
<div id="modal-task_{{ $task->id }}" class="hidden">
<div class="display">
<div class="top">
<div class="title">Opgave #{{ $task->id }} <div class="inline-block text-blue-600 underline text-sm">Se hele opgaven</div>
</div>
<div onclick="closeComponent('modal-task', {{ $task->id }})" class="close-button"><i class="fas fa-times-circle text-gray-700"></i>
</div>
</div>
#include('component.task')
</div>
#endforeach
Right now I get the correct response from the Ajax request.
color: "e53e3e"
company_id: 1
created_date: "2020-11-13"
created_time: "00:00:00"
description: null
id: 8
status_1: null
status_2: null
status_3: null
title: "Overskrift"
But how do I output it like that, with the include also and it should appear many times (its a calendar system that gets tasks from each days)
The Ajax request POST 2 dates (from and to) till a laravel controller which returns the tasks that have the date in between.
<script>
var datePeriodRow = "<?php echo $datePeriodRow; ?>";
var _token = $('input[name=_token]').val();
$.ajax({
url: "/task/get",
type:"POST",
data:{
datePeriodRow:datePeriodRow,
_token: _token
},
success:function(response){
if(response) {
console.log(response);
}
},
});
</script>
What you can do in your "/task/get" endpoint method is to return a view that returns a rendered html. then set the rendered response with javascript in a div element instead of that foreach loop.
So place the foreach code part in an include/partial like partial/tasks.blade.php and in your endpoint method:
/** route: /task/get **/
public function yourTasksMethod(){
//your code that retrieves your tasks
return view('partial.tasks')->with('tasks', $tasks)->render();
}
Keep in mind to clear/empty the div before you make another request to the task/get endpoint.
I have created a fresh Laravel6 project to work out how to register components...
I have cloned ExampleComponent.vue to ExampleComponent2.vue
// ExampleComponent2.vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Example2 Component</div>
<div class="card-body">
I'm an example2 component.
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component2 mounted.')
}
}
</script>
// app.js
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('example-component2', require('./components/ExampleComponent2.vue').default);
// login.blade.php
- I have placed this under the closing tag and #endsection to test on the login page...
<example-component2></example-component2>
I have run "npm run watch" in command line and there are no error messages...
When I load the login route, I open the console to see this error message?
[Vue warn]: Unknown custom element: - did you
register the component correctly? For recursive components, make sure
to provide the "name" option.
(found in )
How do I register extra components???
// login.blade.php - I have placed this under the closing tag and #endsection to test on the login page...
You need an element with the id that you defined in your js/app.js:
const app = new Vue({
el: '#app', // you need an element with id="app". Your vue component will replace this
});
Then put your component inside that element.
//login.blade.php
#extends('layouts.authentication')
#section('content')
<div id="app">
<example-component2/>
</div>
#endsection
I am creating a web app having dashboard using laravel and vue.
When I pass data from controller to vue file data is received properly but when I set it to vue variable the value is not set in the variable. All data is received and its displayed in the console but when I set it to the vue variable, the variable doesn't update its value.
This is my Controller class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
//
public function index()
{
$users=User::all();
return response()->json($users);
}
}
This is myTeam.vue for receiving and displaying the data:
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Example Component</div>
<h1>
This request list
Hello,{{this.items}}
</h1>
<ul class="list-group">
<li class="list-group-item" v-for="t in items">{{items}}</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
//items: []
items:[],
}
},
created() {
var self=this;
axios.get('/allusers').then((response) => self.items=response.data) .catch((error)=>console.log(error));
axios.get('/allusers') .then(response => console.log(response.data));
console.log('Component mounted.'+this.items)
},
}
</script>
Now when I run it the console prints the array properly means data is received but when I set it to items variable the data is not set.
My Output is this:
This is the output image file
Please check it and thanks in advance ...
This is never print items array because it's execute before the ajax response is filled.
console.log('Component mounted.'+this.items)
That's why your console is always blank. You can search about blocking and non blocking programming.
your code have small bug. Update your code and try this:
<h1>
This request list
Hello,{{items}}
</h1>
<ul class="list-group">
<li class="list-group-item" v-for="t in items">{{t}}</li>
</ul>
...
<script>
export default {
data(){
return {
items:[],
}
},
mounted: function () {
this.getList();
}
methods: {
let _this = this;
axios.get('/allusers')
.then((response) => _this.items = response.data)
.catch((error)=>console.log(error));
},
}
</script>
This can help you. Good luck.
I am using Laravel 5.6 and create model named process and a controller with a function that gets all the records of the model:
public function showProcessList(){
return response()->json(Process::all());
}
In the web.php routes file also defined the route to retrieve the records, it works well, i tested the endpoint and i can see the data:
Route::get('process/list', 'ProcessController#showProcessList');
In a blade file i try to show the list creating a Vue component like this:
<!-- Process List -->
<div class="row">
<process></process>
</div>
<script src='{{ asset("public/js/app.js") }}'></script>
file app.js has this:
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('process', require('./components/Process.vue'));
const app = new Vue({
el: '#app'
});
components/Process.vue contains this:
<template>
<div class="tile mb-4 col-md-6 col-lg-12" id="listProcess">
<div class="page-header">
<h3 class="mb-4 line-head">Process List</h3>
</div>
<div v-for="process in processList">
<p>{{ process.name }}</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data () {
return {
processList: [],
}
},
created() {
this.showProcessList();
},
methods: {
showProcessList () {
axios.get('/process/list')
.then(response => {
this.processList = response.body;
});
}
},
}
</script>
Then execute npm run dev and load in web browser the view that invoke the Vue component:
<div class="row">
<process></process>
</div>
<script src='{{ asset("public/js/app.js") }}'></script>
(I have to add public folder to the path of css and js files)
nothing happens, the data doesn't load in the view and i cannot see any error in console.
Testing the endpoint the result is:
[
{
"id": 1,
"created_at": "2018-03-28 04:33:02",
"updated_at": "2018-03-28 04:33:02",
"name": "first_process",
},
]
So, at this point i cannot see where is the error in my code or what i missing?
Thanks.