I have a list with comments, those comments have a moment field, which is a DateTimeField. In this DateTimeField I have for example this --> 2020-06-03T15:32:01.803027 and I want to delete that T character, or replace with a blank space.
I'm using Django for the backend and Vue.js for the frontend.
I was able to remove the Z character by changing the USE_TZ = True to False option in the settings.py file. But I can't remove the T character, that's all I need. I have tried from the frontend to remove the T character using methods and computed properties, but I can't use the replace("T", " ") method on a DateTimeField, I can only use it on a String
<template lang="html">
<div class="container">
<div class="row">
<div class="col text-left">
<h2>Detalles del partido</h2>
</div>
</div>
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<form>
<form #submit="onSubmit">
<div class="form-group row">
<label for="nombreLocal" class="col-sm-2 col-form-label">Local</label>
<div class="col-sm-6">
<input type="text" name="nombreLocal" class="form-control" readonly v-model.trim="form.nombreLocal">
</div>
</div>
<div class="form-group row">
<label for="nombreVisitante" class="col-sm-2 col-form-label">Visitante</label>
<div class="col-sm-6">
<input type="text" name="nombreVisitante" class="form-control" readonly v-model.trim="form.nombreVisitante">
</div>
</div>
<div class="form-group row">
<label for="resultado" class="col-sm-2 col-form-label">Resultado</label>
<div class="col-sm-6">
<input type="text" name="resultado" class="form-control" readonly v-model.trim="form.resultado">
</div>
</div>
<div class="form-group row">
<label for="pronosticoSistema" class="col-sm-2 col-form-label">Pronóstico del sistema</label>
<div class="col-sm-6">
<input type="text" name="pronosticoSistema" class="form-control" readonly v-model.trim="form.pronosticoSistema">
</div>
</div>
<div class="form-group row">
<label for="premio" class="col-sm-2 col-form-label">Premio</label>
<div class="col-sm-6">
<input type="number" name="premio" class="form-control" readonly v-model.trim="form.premio">
</div>
</div>
<div class="form-group row">
<label for="dificultad" class="col-sm-2 col-form-label">Dificultad</label>
<div class="col-sm-6">
<input type="text" name="dificultad" class="form-control" readonly v-model.trim="form.dificultad">
</div>
</div>
<div class="rows">
<div class="col text-left">
<b-button size="sm" variant="primary" :to="{ name:'CreatePronostico', params: {partidoId: this.partidoId} }">
Pronosticar
</b-button>
<b-button size="sm" variant="primary" :to="{ name:'CreateComentario', params: {partidoId: this.partidoId}}">
Comentar
</b-button>
<b-button size="sm" type="submit" class="btn-large-space" :to="{ name: 'PronosticadorUsuario'}">Atrás</b-button>
</div>
</div>
</form>
<br>
<h2>Comentarios</h2>
<br>
<div class="comentarios">
<b-table striped hover
:items="comentarios"
:fields="fields"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc">
<template v-slot:cell(action)="data">
<b-button size="sm" variant="primary" :to="{ name:'CreateComentarioRespuesta', params: {comentarioId: data.item.id} }">
Responder
</b-button>
<b-button size="sm" variant="primary" :to="{ name:'DarMeGusta', params: {comentarioId: data.item.id} }">
Me gusta
</b-button>
<b-button size="sm" variant="primary" :to="{ name:'EditComentario', params: {comentarioId: data.item.id} }">
Editar
</b-button>
<b-button size="sm" variant="danger" :to="{ name:'DeleteComentario', params: {comentarioId: data.item.id} }">
Eliminar
</b-button>
</template>
</b-table>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import swal from 'sweetalert'
import router from "../../router";
export default {
mounted() {
this.checkLoggedIn();
},
data() {
return {
sortBy: 'momento',
sortDesc: false,
partidoId: this.$route.params.partidoId,
form: {
nombreLocal: '',
nombreVisitante: '',
resultado: '',
pronosticoSistema: '',
premio: '',
dificultad: ''
},
fields: [
{ key: 'id', label: 'Número de comentario' },
{ key: 'momento', label: 'Momento', sortable: true},
{ key: 'texto', label: 'Texto' },
{ key: 'meGustas', label: 'Número de "me gustas"', sortable: true},
{ key: 'autor', label: 'Autor' },
{ key: 'comentarioRespuesta', label: 'Responde a' },
{ key: 'action', label: '' }
],
comentarios: []
}
},
methods: {
checkLoggedIn() {
this.$session.start();
if (!this.$session.has("token")) {
router.push("/auth");
}
},
onSubmit(evt){
evt.preventDefault()
const path = `http://localhost:8000/api/v1.0/partidos/${this.partidoId}/`
axios.get(path, this.form).then((response) =>{
this.form.nombreLocal = response.data.nombreLocal
this.form.nombreVisitante = response.data.nombreVisitante
this.form.resultado = response.data.resultado
this.form.pronosticoSistema = response.data.pronosticoSistema
this.form.premio = response.data.premio
this.form.dificultad = response.data.dificultad
})
.catch((error) => {
console.log(error)
})
},
getPartido (){
const path = `http://localhost:8000/api/v1.0/partidos/${this.partidoId}/`
axios.get(path).then((response) =>{
this.form.nombreLocal = response.data.nombreLocal
this.form.nombreVisitante = response.data.nombreVisitante
this.form.resultado = response.data.resultado
this.form.pronosticoSistema = response.data.pronosticoSistema
this.form.premio = response.data.premio
this.form.dificultad = response.data.dificultad
})
.catch((error) => {
console.log(error)
})
},
getComentarios (){
const path = 'http://localhost:8000/api/v1.0/comentarios/'
axios.get(path).then((response) => {
this.comentarios = response.data
})
.catch((error) => {
console.log(error)
})
},
},
computed: {
comentariosFormateados: function (){
var res = [];
for(var i = 0; i < this.comentarios.length; i++){
this.comentarios[i].momento.toISOString().replace('T', '');
res.push(comentarios[i]);
}
return res;
}
},
created() {
this.getPartido(),
this.getComentarios()
}
}
</script>>
<style lang="css" scoped>
</style>
Just return the Django DateTime object formatted however you want, for example:
myDateTime = strftime(MyModel.objects.get(id=id).moment, "%Y-%m-%d %H:%M:%S.%f")
Or:
comment = MyModel.objects.get(id=id)
moment = strftime(comment.moment, "%Y-%m-%d %H:%M:%S.%f")
comment.formatted_moment = moment
...
Then return it to your view in that format (a formatted string).
I've solved with this:
formatMomento(value) { const formattedDate = DateTime.fromISO(value).toLocaleString(DateTime.DATETIME_SHORT); return formattedDate; },
And calling it from the formatter attribute:
fields: [
{ key: 'id', label: 'Número de comentario' },
{ key: 'momento', formatter: "formatMomento", label: 'Momento', sortable: true},
{ key: 'texto', label: 'Texto' },
{ key: 'meGustas', label: 'Número de "me gustas"', sortable: true},
{ key: 'autor', formatter: "nombreDeUsuario", label: 'Autor' },
{ key: 'comentarioRespuesta', label: 'Responde al comentario:' },
{ key: 'action', label: '' }
],
Related
My template
<div class="form-group">
<p class="required">4. How did you hear about our distribution?</p>
<p id="skip">Check all that apply</p>
<b-form-checkbox v-for="item in choices" :key="item" :value="item" v-model="socialMedia" required> {{ item }} </b-form-checkbox>
<b-form-checkbox v-on:click="onclick"> Other: </b-form-checkbox>
<input type="text" class="form-control" :disabled='isDisabled' v-model="other">
<button name="btn" v-show="!isDisabled" #click="addType" required>+</button>
<span class="mt-3">Selected: <strong>{{ socialMedia }}</strong></span>
<br>
<span class="mt-3">Additional check: <strong>{{ other }}</strong> <br><label id="small">Do NOT forget to click PLUS button for optional</label></span>
</div>
My Vue Instance:
export default {
data() {
return {
selected: [],
choices: ['Facebook', 'Instagram', 'Twitter', 'Word of Mouth', 'KMAZ 102.5fm'],
isDisabled: true,
other: '',
}
},
methods: {
onclick() {
this.isDisabled = !this.isDisabled
if (this.selected.length) {
this.selected = this.selected.filter(s => s !== this.other)
}
this.other = ''
},
addType() {
this.socialMedia.push(this.other)
}
}
}
This Vue project will create a checkbox list that allows users to add multiple values and optional. For example, Other box is checked and no values are entered, then click + button, this will add an empty string to the array.
I was trying to do like below, but it did not work:
<div class="form-group">
<p class="required">4. How did you hear about our distribution?</p>
<p id="skip">Check all that apply</p>
<b-form-checkbox v-for="item in choices" :key="item" :value="item" v-model="socialMedia" #change="DetectedEmptyString()"required> {{ item }} </b-form-checkbox>
<b-form-checkbox v-on:click="onclick"> Other: </b-form-checkbox>
<input type="text" class="form-control" :disabled='isDisabled' v-model="other">
<button name="btn" v-show="!isDisabled" #click="addType" required>+</button>
<span class="mt-3">Selected: <strong>{{ socialMedia }}</strong></span>
<br>
<span class="mt-3">Additional check: <strong>{{ other }}</strong> <br><label id="small">Do NOT forget to click PLUS button for optional</label></span>
</div>
export default {
data() {
return {
selected: [],
choices: ['Facebook', 'Instagram', 'Twitter', 'Word of Mouth', 'KMAZ 102.5fm'],
isDisabled: true,
other: '',
}
},
methods: {
onclick() {
this.isDisabled = !this.isDisabled
if (this.selected.length) {
this.selected = this.selected.filter(s => s !== this.other)
}
this.other = ''
},
addType() {
this.socialMedia.push(this.other)
},
DetectedEmptyString() {
return this.socialMedia.filter(x => x !== "")
}
}
}
Expected Output: No matter how many times I click + button, the empty string is automatically removed.
I have dynamic generated form in Vue. Every loop have v-model. Everything work fine. But when I use checkboxes v-model work for all loops not on one like in input type text. Can You help me solved this problem? Below Vue code:
<fieldset>
<div class="form-row mb-2" v-for="input, index in journal" :key="index">
<div class="col-auto">
<label for="date">Data</label>
<Datepicker v-model="input.date" input-class="form-control" :input-attr="{id: 'date', name: 'date'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeStart">Od</label>
<Datepicker type="time" v-model="input.timeStart" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeStart', name: 'timeStart'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeEnd">Do</label>
<Datepicker type="time" v-model="input.timeEnd" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeEnd', name: 'timeEnd'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="players">Lista obecności</label>
<div class="form-check" v-for="item in input.players">
<input v-model="item.checked" type="checkbox" class="form-check-input" :id="'id-'+item.id+'set'+index">
<label class="form-check-label" :for="'id-'+item.id+'set'+index">{{ item.fullName }}</label>
</div>
</div>
<div class="col-auto">
<label for="description">Opis</label>
<textarea v-model="input.description" class="form-control" rows="7" id="description" placeholder="Opis"></textarea>
</div>
<div class="col-auto" #click="addInput" v-show="index == journal.length-1 && journal.length < 16">
<ButtonVue style="margin-top: 30px;" title="Dodaj" type="button" cancelWidth="true" color="btn-success"><i class="fas fa-plus"></i></ButtonVue>
</div>
<div class="col-auto align-self-start" #click="removeInput(index)" v-show="index || ( !index && journal.length > 1)">
<ButtonVue style="margin-top: 30px;" title="Usuń" type="button" cancelWidth="true" color="btn-danger"><i class="fas fa-minus"></i></ButtonVue>
</div>
</div>
</fieldset>
data() {
return {
contact: [],
journal: [{
date: "",
timeStart: "",
timeEnd: "",
players: "",
description: ""
}],
contacts: [],
}
},
Methods:
Method for creating dynamic form
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact,
description: ""
});
},
And here is the method which gets players from contacts
getContacts() {
this.pageLoader = true;
this.$http.get('/pkpar/get-contacts')
.then(({
data
}) => {
this.contacts = data.contacts;
for(let i=0; i<this.contacts.length; i++)
{
this.contact.push({'id': this.contacts[i]['id'], 'fullName' :
this.contacts[i]['fullName'], 'checked': true});
}
this.journal[0].players = this.contact;
this.pageLoader = false;
})
.catch(error => {
console.log(error);
});
},
Your addInput method creates and pushes new object into journal array, but each object created this way has a players property which references same array (this.contact)
The Difference Between Values and References in JavaScript
Easiest (but not most optimal) way to handle this is to create a copy of the array and objects inside for each new journal:
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact.map((player) => ({ ...player })),
description: ""
});
},
I want to insert the value inserted into an input in the database using Angular as the frontend and php as the backend but I'm not able to insert the input value into the method along with the user.id.
The input is for the reason of moderation when clicking on disapprove it is necessary to pass the reason but it is not entering.
import { Component, OnInit, TemplateRef } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { observerMixin } from '#rodrigowba/observer-component';
import { ResponseData, DefaultResponse } from '#rodrigowba/http-common';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { ActionPayload } from '~/ngrx';
import {
HotsiteUser,
HotsiteUsersFacade,
HotsiteUsersFormService,
RegistrationStatusTypes,
UpdateHotsiteUserRequest,
HotsitePointsPrebase,
} from '~/admin/users';
import {
updateHotsiteUser,
hotsiteUserUpdated,
hotsiteUserUpdateFailed,
hotsiteUserRegistrationModerated,
hotsiteUserModerateRegistrationFailed
} from '~/admin/users/state';
import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
#Component({
templateUrl: './view.component.html',
})
export class ViewComponent extends observerMixin() implements OnInit {
user$: Observable<HotsiteUser>;
pointsPrebase$: Observable<HotsitePointsPrebase[]>;
customFields$: Observable<{
field: string,
value: string
}[]>;
registrationStatusTypes = RegistrationStatusTypes;
form: FormGroup;
modalRef: BsModalRef;
submiting = false;
constructor(
private hotsiteUsersFacade: HotsiteUsersFacade,
private hotsiteUsersFormService: HotsiteUsersFormService,
private modalService: BsModalService,
private toastr: ToastrService
) {
super();
this.form = this.hotsiteUsersFormService.updateForm();
}
ngOnInit() {
this.user$ = this.hotsiteUsersFacade.selectCurrentHotsiteUser();
this.customFields$ = this.user$.pipe(
map(user => Object.values(user.custom_fields)),
map(customFields => customFields.map(customField => {
let value = customField.value;
if (Array.isArray(value)) {
value = value.join(', ');
}
return {
field: customField.field,
value
};
}))
);
this.pointsPrebase$ = this.user$.pipe(
map(user => user.id),
distinctUntilChanged(),
tap(id => {
this.hotsiteUsersFacade.fetchHotsitePointsPrebase(id);
}),
switchMap(id => this.hotsiteUsersFacade.selectHotsitePointsPrebaseByHotsiteUser(id))
);
this.observe(this.user$).subscribe(user => {
this.form.patchValue(user);
});
this.observe(
this.hotsiteUsersFacade.ofType(updateHotsiteUser)
).subscribe(() => {
this.submiting = true;
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<ResponseData<HotsiteUser>>>(
hotsiteUserUpdated,
hotsiteUserRegistrationModerated
)
).subscribe(action => {
const { message, data } = action.payload;
this.submiting = false;
this.toastr.success(message);
});
this.observe(
this.hotsiteUsersFacade.ofType<ActionPayload<DefaultResponse>>(
hotsiteUserUpdateFailed,
hotsiteUserModerateRegistrationFailed
)
).subscribe(action => {
const { message } = action.payload;
this.submiting = false;
this.toastr.error(message);
});
}
onSubmit(id: string, data: UpdateHotsiteUserRequest) {
this.hotsiteUsersFacade.updateHotsiteUser(id, data);
}
openModal(template: TemplateRef<any>, size = 'modal-md') {
this.modalRef = this.modalService.show(template, { class: size });
}
approveRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: true,reason });
}
rejectRegistration(id: string,reason: string) {
this.hotsiteUsersFacade.moderateRegistrationHotsiteUser(id, { approved: false,reason });
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<form [formGroup]="form" (ngSubmit)="onSubmit(user.id, form.value)" >
<div class="row mb-3">
<div class="col-12">
<div class="form-group">
<label>Name</label>
<input type="text" [value]="user.name" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>E-mail</label>
<input type="text" [value]="user.email" class="form-control" readonly />
</div>
</div>
<div class="col-12 col-lg-6">
<div class="form-group">
<label>Document</label>
<input type="text" [value]="user.document" class="form-control" readonly />
</div>
</div>
<div class="col-12" *ngFor="let customField of customFields$ | async">
<div class="form-group">
<label>{{ customField.field }}</label>
<input type="text" [value]="customField.value" class="form-control" readonly />
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="admin" color="primary" ></mat-slide-toggle>
<label class="ml-2">Admin</label>
</div>
</div>
<div class="col-auto">
<div class="form-group">
<mat-slide-toggle formControlName="active" color="primary" ></mat-slide-toggle>
<label class="ml-2">Active</label>
</div>
</div>
</div>
<ng-container *ngIf="pointsPrebase$ | async as pointsPrebase">
<div class="row mb-3" *ngIf="pointsPrebase.length > 0">
<div class="col-12">
<h4 class="font-16 font-weight-bold">Points</h4>
</div>
<div class="col-12 col-lg-6">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Chave</th>
<th class="text-center">Points</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let points of pointsPrebase">
<td>{{ points.value }}</td>
<td class="text-center">{{ points.points }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</ng-container>
<div class="form-row">
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">
<div class="col-auto">
<label>Reason</label>
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-success"
(click)="approveRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Approved </app-loading-label>
</button>
</div>
<div class="col-auto">
<button
type="button"
class="btn btn-danger"
(click)="rejectRegistration(user.id,form.reason)"
>
<app-loading-label [loading]="submiting">Repproved </app-loading-label>
</button>
</div>
</ng-container>
<div class="col text-right">
<button
type="submit"
class="btn btn-orange"
[disabled]="form.invalid || submiting"
>
<app-loading-label [loading]="submiting">Salvar</app-loading-label>
</button>
</div>
</div>
</form>
Error:
Property 'reason' does not exist on type 'formGroup'
As user776686 suggested, there is a formControlName missing linked to "reason" field.
To get the field value in HTML you should access to the FormGroup controls:
(click)="approveRegistration(user.id, form.controls.reason.value)"
Also you can create a "get" property in TS code and then access to it in HTML:
get reason() {
return this.form.controls.reason.value;
}
(click)="approveRegistration(user.id, reason)"
BTW, a field can be accessed too through the "get" method of a FormGroup:
get reason() {
return this.form.get('reason').value;
}
It expects a control with the attribute formControlName="reason" which is not present here:
<input type="text" name="reason" placeholder="Reason of moderation..." class="form-control"/>
This might be a reason.
If that doesn't help, you my also want to look into the *ngIf condition here:
<ng-container *ngIf="user.registration_status === registrationStatusTypes.AwaitingModeration">
I am attempting to add objects into an array I declared in Vue instance data object. I can set the values in the state's purchase object, but when I push data into the orders queue array, the empty array is not populated. The function is being triggered, but the array does not update.
Here is my form:
<form
v-on:submit.prevent="queuePurchase"
class="form-inline row"
id="order-creation-form"
method="POST"
>
#csrf
<autocomplete-field
sizing="col-xs-12 col-sm-3 col-md-3"
name="customer"
label="Customer"
:data="{{ json_encode($customers) }}"
v-on:setcustomer="setCustomer($event)"
></autocomplete-field>
<div class="col-xs-12 col-sm-3 col-md3 form-group d-flex flex-column align-items-start">
<label for="phone">Product</label>
<select
v-model="purchase.product"
class="form-control w-100"
name="product"
aria-describedby="productHelpBlock"
required
>
#foreach ($products as $product)
<option :value="{{ json_encode($product) }}">
{{ $product->name }}
</option>
#endforeach
</select>
<small id="productHelpBlock" class="form-text text-muted">
Select a product
</small>
</div>
<div class="col-xs-12 col-sm-3 col-md-3 form-group d-flex flex-column align-items-start">
<label for="phone">Quantity</label>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
class="form-control w-100"
aria-describedby="productHelpBlock"
required
>
<small id="productHelpBlock" class="form-text text-muted">
Product quantity
</small>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success icon-button d-flex">
<i class="material-icons">add</i>
<span> Q U E U E</span>
</button>
</div>
</form>
And here is my javascript:
require("./bootstrap");
window.Vue = require("vue");
Vue.component("queue-table", require('./components/QueueTable.vue'));
Vue.component("autocomplete-field", require('./components/AutocompleteField.vue'));
const purchaseApp = new Vue({
el: "#purchase-app",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
}
},
methods: {
setCustomer: function(customerObj) {
this.purchase.customer = customerObj;
},
queuePurchase: function() {
this.queue.push( this.purchase );
}
}
});
Could someone please explain what & why it is happening?
The push() method ought to add purchase objects to the queue array, but as #FK82 pointed out in his comment, push() is adding multiple references to the same purchase object. This means that if you change the object by increasing the quantity, every purchase's quantity property will be updated.
You can give that a try here:
const exampleComponent = Vue.component("example-component", {
name: "exampleComponent",
template: "#example-component",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
};
},
methods: {
queuePurchase() {
this.queue.push( this.purchase );
}
}
});
const page = new Vue({
name: "page",
el: ".page",
components: {
"example-component": exampleComponent
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
<div>
<p>The Queue has {{ this.queue.length }} items.</p>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
placeholder="Quantity"
>
<button #click="queuePurchase">
Add to Queue
</button>
<pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
</div>
</template>
<div class="page">
<example-component></example-component>
</div>
Instead of push()ing a reference to the same purchase object, try creating a shallow copy with Object.assign({}, this.purchase) or by using the spread operator. Here's an example that uses the spread operator and then push()es the copy onto the queue:
const exampleComponent = Vue.component("example-component", {
name: "exampleComponent",
template: "#example-component",
data() {
return {
queue: [],
purchase: {
product: null,
customer: null,
quantity: null
}
};
},
methods: {
queuePurchase() {
this.queue.push({...this.purchase});
}
}
});
const page = new Vue({
name: "page",
el: ".page",
components: {
"example-component": exampleComponent
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="example-component">
<div>
<p>The Queue has {{ this.queue.length }} items.</p>
<input
v-model="purchase.quantity"
type="number"
min="1"
name="product"
placeholder="Quantity"
>
<button #click="queuePurchase">
Add to Queue
</button>
<pre>{{ JSON.stringify(this.queue, null, 2) }}</pre>
</div>
</template>
<div class="page">
<example-component></example-component>
</div>
Can someone help me generate dynamic v-model values?
<div v-for="car in cars">
<div class="row">
<div class="col-md-2">
<p v-model="car.attr_1">{{ car.attr_1 }}</p>
</div>
<div class="col-md-3">
<p v-model="car.attr_2">{{ car.attr_2 }}</p>
</div>
<div class="col-md-2">
<p v-model="car.attr_3">$ {{ car.attr_3 }}</p>
</div>
<div class="col-md-2">
<p><input type="text" class="" placeholder="Quantity" v-on:click="addCar(car)"/></p>
</div>
</div>
</div>
<script>
module.exports = {
data: function () {
return {
cars: ''
}
},
methods: {
getCars: function () {
var self = this;
$.ajax({
type: "GET",
url: '/api/cars',
success: function(data) {
self.cars = data;
}
});
}
}
}
</script>
Sample JSON response - note how all the properties are different..:
cars: [
{
make: 'Audi',
model: 'R8',
color: 'red'
},
{
make: 'Chevy',
tires: 'All Season',
weight: 30
},
{
make: 'Chevy',
tires: 'Summer',
color: 'black'
},
{
make: 'Ford',
weight: 40,
gps: true
}
]
I have an ajax call that returns an array of cars objects. The problem is all the objects returned have variable attributes. Therefore, how can vue.js handle these variable attributes for v-model? I've tried things like v-model="car[ {{attr_1}} ]" but these all return errors.. Can someone help?
Thanks in advance!
You can do it something like:
<div v-for="car in cars">
<div class="row">
<div class="col-md-2" v-if="car.make">
<p v-model="car.make">{{ car.make }}</p>
</div>
<div class="col-md-3" v-if="car.tires">
<p v-model="car.tires">{{ car.tires }}</p>
</div>
<div class="col-md-2" v-if="car.color">
<p v-model="car.color">$ {{ car.color }}</p>
</div>
<div class="col-md-2">
<p><input type="text" class="" placeholder="Quantity" v-on:click="addCar(car)"/></p>
</div>
</div>
</div>
alternatively, You can also write a method, which given car object and attribute, will return corresponding value:
function(car, attr){
return car[attr];
}