I'm having a trouble on how can I implement conditional rendering inside v-for in laravel vue js
based on the documentation of vue js v-for and v-if together is not recommended. It would be great if anybody could help me out, thank you so much in advance!.
This is what flow looks like I know the format is incorrect
<tr v-for="user in users" :key="user.id" :value="user.id">
<td>
<v-if =user.gender="Male" >
<span>Male - {{ user.gender }}</span>
<v-else>
<span>FeMale - {{ user.gender }}</span>
</td>
</tr>
script
<script>
export default {
data() {
return {
users: [],
}
},
created() {
this.getUsers();
},
mounted() {
},
methods: {
getUsers() {
axios.get(BASE_URL + "/users/listUsers").then(response => {
this.users = response.data;
});
},
},
}
</script>
Your v-if syntax is completely incorrect. Let's fix it first.
<tr v-for="user in users" :key="user.id" :value="user.id">
<td>
<span v-if="user.gender=='Male'">Male - {{ user.gender }}</span>
<span v-else>FeMale - {{ user.gender }}</span>
</td>
</tr>
If <span> isn't necessary I would use this:
<tr v-for="user in users" :key="user.id" :value="user.id">
<td v-if="user.gender=='Male'">Male - {{ user.gender }}</td>
<td v-else>FeMale - {{ user.gender }</td>
</tr>
Actually, there is a better way:
<tr v-for="user in users" :key="user.id" :value="user.id">
<td>{{ user.gender=="Male" ? "Male" : "FeMale" }} - {{ user.gender }}</td>
</tr>
v-for and v-if can't be used in the same tag. This is not the case in your code. When you need v-for and v-if together, you should use a computed property, and return the array/object that is filtered based on the condition, then inject it into v-for.
Let's say you need something like this:
<tr v-for="user in users" :key="user.id" v-if="user.id > 10">...</tr>
In this case, we use computed property:
computed: {
filteredUsers() {
return this.users.filter(user => user.id > 10);
}
}
and in the template:
<tr v-for="user in filteredUsers" :key="user.id">...</tr>
I think there is a misunderstanding. You should not use v-if and v-for on the same element the way you used it is fine. You can see an example here.
If you don't want to have v-if at all since you aren't rendering completely different elements you could use ternary operation in mustaches:
<tr v-for="user in users" :key="user.id" :value="user.id">
<td>
<span>{{ user.gender === 'Male' ? `Male - ${user.gender}` : `Female - ${user.gender}` }}</span>
</td>
</tr>
Related
I have two tables first one simple html with no datatables, second with datables. My purpose transform first table two datatables second. But I had two main problems Grazinimo terminas column is using laravel #if and column Veiksmai using if statemens as well how can i add those as custom columns in second table.
First table code
<table class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Grąžinimo terminas</th>
<th>Vardas</th>
<th>Pavardė</th>
<th>Kliento nr.</th>
<th>Veiksmai</th>
</thead>
<tbody>
#foreach($paskolinimai as $p)
<input type="hidden"
value="{{ $skirtumas = \Carbon\Carbon::parse(\Carbon\Carbon::today()->toDateString())->diffInDays( \Carbon\Carbon::parse( $p->terminas),false) }}">
<tr>
<td>{{ $p->pavadinimas }}</td>
<td>{{ $p->miestas }}</td>
<td>{{ $p->isdavimo_data }}</td>
#if($p->grazinimo_data != NULL)
<td>
<strong style="color: green;">Knyga grąžinta!</strong>
</td>
#elseif($skirtumas > 0)
<td>
Liko <strong style="color: crimson;">{{ $skirtumas }}</strong> dienų.
</td>
#elseif($skirtumas < 0) <td>
<strong style="color: crimson;">Terminas praėjo!</strong>
</td>
#elseif($skirtumas = 0)
<td>
<strong style="color: crimson;">Šiandien paskutinė grąžinimo diena!</strong>
</td>
#endif
<td>{{ $p->vardas }}</td>
<td>{{ $p->pavarde }}</td>
<td>{{ $p->klientasnr }}</td>
#if($p->grazinimo_data == null)
<td><a href="{{ url('patvirtinti-grazinima-'.$p->id.'-'.$p->bookid) }}"
class="btn btn-primary">Grąžinimas</a> </td>
#else
<td>
<p class="btn btn-success">Grąžinta</p>
</td>
#endif
#endforeach
</tr>
</tbody>
</table>
Second table code
<script>
$(document).ready(function () {
var darbuotojai = $('#paskolinimai').DataTable({
processing: true,
serverSide: true,
ajax:
{
url: '{!! route('get.paskolinimai') !!}'
},
columns: [
{ data: 'pavadinimas', name: 'pavadinimas' },
{ data: 'miestas', name: 'miestas' },
{ data: 'isdavimo_data', name: 'isdavimo_data' },
{ data: 'vardas', name: 'vardas' },
{ data: 'pavarde', name: 'pavarde' },
],
'oLanguage': {
'sSearch': "Paieška:",
'sZeroRecords': "Nerasta atitinkančių įrašų",
'sLengthMenu': "Rodyti _MENU_ įrašų",
'sInfo': "Nuo _START_ iki _END_ viso _TOTAL_ įrašų",
'sProcessing': "Apdorojama...",
'sLoadingRecords': "Kraunama...",
'sInfoFiltered': " - (filtruojama iš _MAX_ įrašų)",
'oPaginate': {
'sFirst': "Pirmas",
'sLast': "Paskutinis",
'sNext': "Sekantis",
'sPrevious': "Ankstesnis"
},
},
'sDom': '<"top"lfip>rt<"bottom"p><"clear">',
});
});
</script>
<table id="paskolinimai" class="table table-bordered">
<thead class="bg-warning">
<th>Knygos pavadinimas</th>
<th>Miestas</th>
<th>Išdavimo data</th>
<th>Vardas</th>
<th>Pavardė</th>
</thead>
<tbody></tbody>
</table>
</div>
So how can i add Grazinimo terminas and veiksmai correctly to the second table
I recommend you to use this package:
https://yajrabox.com/docs/laravel-datatables/master/installation
then go to section add column:
https://yajrabox.com/docs/laravel-datatables/master/add-column
and in your code will be like that:
->addColumn('intro', function(User $user) {
if($condtion){return $result}
})
I am developing a project in Laravel-5.8.
Controller
public function index()
{
$identities = AppraisalIdentity::where('company_id', $userCompany)->get();
return view('appraisal.appraisal_identities.index')->with('identities', $identities);
}
index.blade.php
<tbody>
#foreach($identities as $key => $identity)
<td>
{{$key+1}}
</td>
<td>
{{$identity->appraisal_name ?? '' }}
</td>
<td>
{{ $identity->is_current ?? '' }}
</td>
#endforeach
What I want to achieve is that when is_current is 0, it should display No in red colour and when is_current is 1, should display Yes in green colour.
How do I achieve this?
Thank you
You can use the Blade unescaped bracket notation for this to add a css span with style or class like this:
{!! $identity->is_current ? "<span class='green'>Yes</span>" : "<span class='red'>No</span>" !!}
Where red and green are style classes for your colors.
You can try Laravel blade's if statement:
<td>
#if ($identity->is_current)
<span style="color: green;">Yes</span>
#else
<span style="color: red;">No</span>
#endif
</td>
However when I click the button only the first button contains the user id the rest returns null. Also depending on where I place my id tag on HTML the data-id is empty. How can I pass data from my blade view to Vue.js for an Axios post request which contains the post Id ?
const app = new Vue({
el: '#like',
data: {
post_id: '',
},
methods: {
whichId: function(event) {
this.post_id = this.$el.getAttribute('data-id');
console.log(this.$el.getAttribute('data-id'));
}
}
})
<div class="container" id="like">
<table class="table mt-5">
<tbody>
#foreach ($posts as $post)
<tr>
<td><img src="images/profil.svg" class="rounded-circle border border-dark ml-2" width="60" height="60" alt=""></td>
<td>{{ $post->username->name }}</td>
<td>{{ $post->content }}</td>
<td>
<button v-on:click="whichId" data-id="{{ $post->id }}">
<img src="/images/heart.svg" width="30" height="30" />
</button>
</td>
<td>{{ $post->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
The this.$el is going to refer to the element. When using PHP to iterate through records. You should pass the id through the click event handler. Thanks to Wilk Randall on laracast for the help.
methods: {
whichId (postId) {
console.log(postId);
}
}
<td><button v-on:click="whichId({{ $post->id }})"<img src="/images/heart.svg" width="30"></button></td>
I am trying to create a feature on my web application that allows the user to see the posts between two dates. However, I am having problems trying to pass data from my database to my blade template. Instead of retrieving the created_at date of the post I receive the date "1/01/1970" and the job number does not appear.
First I added the routes in my web.php file:
Route::get('/search', function () {
return view('search');
});
Route::post('/select', 'PostController#getDate');
In my PostController.php file, I added my getDate Function:
public function getDate(Request $request){
$posts = DB::table('jobs')
->whereBetween('created_at', [$request->fdate, $request->sdate])
->get();
$posts->created_at = $request->created_at;
$posts->job_number = $request->job_number;
return view('result', ['posts' => $posts]);
}
My search.blade.php which is the form:
<form method="POST" action="/select">
{{ csrf_field() }}
<div class="form-group">
<label>First Date:</label>
<input type="date" class="form-control" name="fdate">
</div>
<div class="form-group">
<label>Second Date:</label>
<input type="date" class="form-control" name="sdate">
</div>
<input type="submit" value="Get Post Between" class="btn btn-primary">
</form>
My result.blade.php file which shows the post.
#if(count( $posts )>0)
<table class="table table-bordered table-striped">
<thead>
<th>Date created</th>
<th>Job Number</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{ date('j/m/Y', strtotime($posts->created_at)) }}</td>
<td>{{ $posts->job_number }}</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 class="text-center">No Post from Selected Range</h3>
#endif
I am honestly confused, I have used the correct variables.
Here you are appending properties to a collection object not to each element
$posts->created_at = $request->created_at;
$posts->job_number = $request->job_number;
to add these properties to each element you should use map() or loop the elements.
foreach($posts as $post) {
$post->created_at = $request->created_at;
$post->job_number = $request->job_number;
}
you should use the single post not the whole array to get the date
change
<td>{{ date('j/m/Y', strtotime($posts->created_at)) }}</td>
with
<td>{{ date('j/m/Y', strtotime($post->created_at)) }}</td>
same stuff for the {{ $posts->job_number }} -> {{ $post->job_number }}
I'm having hard time on this.
My specific error is on this code: If I'll try to remove it everything works but I need to display the data columns. I don't understand why it cause an error.
<select>
<option v-for="column in columns">{{ column }}</option>
</select>
My app.js
import Vue from 'vue'
import DataViewer from './components/DataViewer.vue'
const app = new Vue({
el: '#app',
components: {
DataViewer
},
data: {
}
});
My DataViwer.vue
<template>
<div class="dv">
{{ title }}
</div>
<select>
<option v-for="column in columns">{{ column }}</option>
</select>
</template>
<script type="text/javascript">
import Vue from 'vue'
import axios from 'axios'
export default {
props: ['source', 'title'],
data(){
return {
model: {},
columns: {}
}
},
created(){
this.fetchIndexData()
},
methods: {
fetchIndexData(){
var vm = this
axios.get(this.source)
.then(function(response){
Vue.set(vm.$data, 'model', response.data.model)
Vue.set(vm.$data, 'columns', response.data.columns)
console.log(vm.$data.columns);
})
.catch(function(response){
console.log(response)
})
}
}
}
</script>
My ajax results:
I had the same warn and I found this decision: http://github.com.proxy.parle.co/ElemeFE/element/issues/4137
<el-tag v-for="tag in tags">
=>
<el-tag v-for="(tag, index) in tags" :key="index">
I faced that error because of a syntax mistake in for loop
the problem was the typo issue in src attribute in img tag!
<img class="m-widget__img" src="{{article.img_thumbnail}}" alt="">
which is totally wrong! it have to be like:
<img class="m-widget__img" :src="article.img_thumbnail" alt="">
as you know in these cases we have to bind the parameter to use in that attribute,
so first of all search for similar mistakes...
hope be helpful
To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key
<option v-for="column in columns">{{ column }}</option>
change it to
<option v-for="column in columns" :key="column">{{ column }}</option>
I have the same warn and figure it out that it happen when writing something else outside the loop:
This is OK
<template>
<table class="responsive-table">
<thead>
<tr>
<th class="no-print" style="width:1%;">
<label>
<input type="checkbox" v-model="selectAll"><span></span>
</label>
</th>
<th style="width:85%">Fecha</th>
<th style="width:14%">Acciones</th>
</tr>
</thead>
<tbody>
<tr v-for="list in messages" :key="list.id">
<td class="no-print" style="width:1%;">
<label><input type="checkbox" name="print_messages[]" v-model="selected" :value="list.id"><span></span></label>
</th>
<td class="view-link">{{list.formatted_date}}</td>
<td></td>
</tr>
</tbody>
</table>
This is NOT OK and through the error "(Emitted value instead of an instance of Error)"
<template>
<h1>I AM TRYING TO ADD A TITLE IN HERE</h1>
<table class="responsive-table">
<thead>
<tr>
<th class="no-print" style="width:1%;">
<label>
<input type="checkbox" v-model="selectAll"><span></span>
</label>
</th>
<th style="width:85%">Fecha</th>
<th style="width:14%">Acciones</th>
</tr>
</thead>
<tbody>
<tr v-for="list in messages" :key="list.id">
<td class="no-print" style="width:1%;">
<label><input type="checkbox" name="print_messages[]" v-model="selected" :value="list.id"><span></span></label>
</th>
<td class="view-link">{{list.formatted_date}}</td>
<td></td>
</tr>
</tbody>
</table>
** CHECK THE FIRST LINE AFTER OPENING "template" tag
Any clue on this?
Oh, BTW, I am learning VUEJS brute force style... so be nice ;p
In my case the problem was writing this:
<div :v-if="a>b"/>
<div v-else/>
Instead of this:
<div v-if="a>b"/>
<div v-else/>
Afaik you usually get this error when you have made a syntactic error in your template. It has usually nothing to do with the javascript and logic of your application.