I have a Personnel table bound to an array of objects that is coming from VueJs. The last column on the table is a button for editing each record.
I'd like to show a modal popup when the edit button is clicked and bind the textboxes to the properties of the personnel that I want to edit. It should update the table and the source of the data when the save button on the modal popup is clicked.
But I am stuck on passing the object or even just the key to the component so I can load the data or bind the edited object into my textboxes.
JS
var app = new Vue({
el: '#my-app',
data: {
personnels: [
{
id: 1,
firstName: 'Billy',
lastName: 'Bob',
email: 'bb#kewl.com'
},
{
id: 2,
firstName: 'Mike',
lastName: 'Coilers',
email: 'mco#kewl.com'
},
{
id: 3,
firstName: 'Fred',
lastName: 'Just',
email: 'freju#gmail.com'
},
{
id: 4,
firstName: 'Tori',
lastName: 'Drury',
email: 'smstua#gmail.com'
}
]
},
methods: {
showPersonnelEditor: function () {
// how do i pass data to the personnelEditor component?
}
}
});
Vue.component('personnel-editor', {
prop: ['personnel']
});
HTML
<div id="my-app">
<table classs="table" width="100%">
<tr>
<th>
Id
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Email
</th>
<th>
Actions
</th>
</tr>
<tr v-for="personnel in personnels">
<td>
{{ personnel.id }}
</td>
<td>
{{ personnel.firstName }}
</td>
<td>
{{ personnel.lastName }}
</td>
<td>
{{ personnel.email }}
</td>
<td>
<button v-on:click="showPersonnelEditor">Edit</button>
</td>
</tr>
</table>
<personnel-editor inline-template><div class="modal fade" >
<div class="modal-dialog">
<div class="modal-header">
header
</div>
<div class="modal-content">
<div class="form-group row">
<div class="col-lg-12">
<label>Id</label>
<input type="text" v-model="personnel.Id" />
</div>
<div class="form-group row">
<div class="col-lg-12">
<label>First Name</label>
<input type="text" v-model="personnel.firstName" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-lg-12">
<label>Last Name</label>
<input type="text" v-model="personnel.lastName" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-12">
<label>Email</label>
<input type="text" v-model="personnel.Email" />
</div>
</div>
</div>
<div class="modal-footer">
oh mah foot
</div>
</div>
</div>
</div></personnel-editor>
You can try :
<button v-on:click="showPersonnelEditor(personnel)">Edit</button>
Then in showPersonnelEditor method :
showPersonnelEditor: function (personnel) {
this.selectedPersonnel = personnel; //make sure to declare selectedPersonnel in data
}
And finally in your html template :
<personnel-editor inline-template :personnel=selectedPersonnel><div class="modal fade" >
Hote it helps.
Edit for binding the result of the modal :
You can emit an event when the modal is closed, either with a button or any other closed event depending on your implementation.
This is a code sample for emitting en event :
whenModalClosedMethod() {
this.$emit('personnel-edited', personnel);
}
Then in your template :
<personnel-editor inline-template :personnel=selectedPersonnel v-on:personnel-edited="updatePersonnel">
And then in your root component add a method :
updatePersonnel: function(personnel) {
//look for the correct entry by id in your personnels array and update it
}
Related
I have a table that will retrieve all the users information along with a button that will open a popup modal to edit the user details. The Modal will display the user data correctly , but when I try to save the changes that the user has entered on a button click, the value of the textboxes will be the first row of the table bot the one that the user entered. How can I get the value of the textbox that is currently displayed on the modal popup.
My View:
<div class="form-group" align="center">
<table id="AllUsersTable2" class="display" style="width:100%;">
<tr>
<th>id</th>
<th>FullName</th>
<th>username</th>
<th>MobileNumber</th>
<th>Email</th>
<th>IsActiveText</th>
<th>RoleName</th>
<th>Edit</th>
</tr>
#foreach (var user in Model.UserTable)
{
<tr>
<td>#user.NationalID</td>
<td>#user.FullName</td>
<td>#user.username</td>
<td>#user.MobileNumber</td>
<td>#user.Email</td>
<td>#user.IsActiveText</td>
<td>#user.RoleName</td>
<td><button class="btn btn-primary" id="" data-toggle="modal" data-target="##user.NationalID">عرض</button></td>
</tr>
//PopUp Starts HERE
<div class="modal fade" id="#user.NationalID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
#using (Html.BeginForm(Html.BeginForm(null, null, FormMethod.Post, new { #id = "UpdateUserForm" })))
{
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="NationalID" class="control-label">رقم الهوية</label>
<input type="text" id="UpdateuNationalID" name="NationalID" value="#user.NationalID" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="FullName" class="control-label">الإسم</label>
<input type="text" id="UpdateFullName" name="FullName" value="#user.FullName" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="username" class="control-label">اسم المستخدم</label>
<input type="text" id="Updateusername" name="username" value="#user.username" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="MobileNumber" class="control-label">رقم الهاتف</label>
<input type="text" id="UpdateMobileNumber" name="MobileNumber" value="#user.MobileNumber" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Email" class="control-label">البريد الإلكتروني</label>
<input type="text" id="UpdateEmail" name="Email" value="#user.Email" class="control-label">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="IsActive" class="control-label">حالة المستدم</label>
<select name="IsActive" id="UpdateIsActive">
<option value="">...</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="RoleId" class="control-label">البريد الإلكتروني</label>
<select name="RoleId" id="UpdateRoleId">
<option value="">...</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
</div>
</div>
</div>
</div>
}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn">تعديل المستخدم </button>
</div>
</div>
</div>
</div>
//PopUp END HERE
}
</table>
</div>
My Click Event:
$('body').on('click', '.UpdateUserBtn', function (e) {
var NationalID = $("#UpdateuNationalID").val();
console.log(NationalID);
var username = $('#Updateusername').val();
var FullName = $('#UpdateFullName').val();
var MobileNumber = $('#UpdateMobileNumber').val();
var Email = $('#UpdateEmail').val();
var RoleId = $('#UpdateRoleId').val();
var IsActive = $('#UpdateIsActive').val();
$.post("#Url.Action("UpdateUser", "Home")", { NationalID: NationalID, username: username, FullName: FullName, MobileNumber: MobileNumber, Email: Email, RoleId: RoleId, IsActive: IsActive }, function (data) {
if (data.Result == 1) {
//closePopup();
$.notify(
"تم الحفظ بنجاح",
{
globalPosition: 'top center',
className: 'success'
}
);
}
else {
console.log(data);
$.notify(
"حدث خطأ أثناء الحفظ ",
{
globalPosition: 'top center',
className: 'danger'
}
);
// console.log(data);
}
});
});
The problem here for example the value of $("#UpdateuNationalID").val(); will be always the value of first row of the table not the value that is displayed on the popup..
The problem as said by #Carsten Løvbo Andersenis is that you are using the same Id when generating the HTML, so your jQuery var NationalID = $("#UpdateuNationalID").val(); will take the first value that he find.
To solve this, you need to assign a different Id in every loop, for example you can do ad follow if we suppose that NationalID is unique :
<input type="text" id='UpdateuNationalID #user.NationalID' name="NationalID" value="#user.NationalID" class="control-label" required>
EDIT:
You have to create a function for example SaveMe instead to wait for the event click, and you need to send a value on click in your modal:
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn" onclick="SaveMe(#user.NationalID)">تعديل المستخدم </button>
and your event listner first line $('body').on('click', '.UpdateUserBtn', function (e) {
change it to be a function:
function SaveMe(myId) {
var str1 = 'UpdateuNationalID ' + myId;
var NationalID = document.getElementById(str1).innerHTML;
// or
var NationalID = document.getElementById(str1).value;
// then
console.log(NationalID);
I want to build a pop-up modal edit form to change individual table values in a dynamic grid. Right now, the input fields appear on button click using the function editToggle(i). No more than 4 input fields will ever appear because they are meant to edit the 4 values in my data model. However, the input fields (and values) are being dynamically generated with *ngFor. I need some way to pass/copy those input fields to my modal to edit there instead of on the grid itself (where they currently appear after clicking the edit button).
I have tried to use [(ngModel)] to clone but it does not work. I have tried to pass them using functions but the values return null. Because the HTML only shows one input field (because they are being dynamically created with *ngFor) I do not know of a way to individually pass the values.
<div>
<table align="center">
<tr>
<th>
List of Providers
</th>
</tr>
</table>
<table id="thetable" align="center">
<tr>
<th>Application ID</th>
<th>Client Name</th>
<th>Version</th>
<th>API Key</th>
<th>Protected Secret</th>
<th>EDIT/DELETE</th>
</tr>
<tr ng-app="tblRowApp" *ngFor="let prov of providers; let i = index">
<td *ngFor="let col of columns">
<span class="field" *ngIf="i !== index">
{{prov[col]}}
</span>
<span *ngIf="i === index">
<input [(ngModel)]="inputClientName" class="table" value="{{prov[col]}}" (change)="EditItem(i, col, $event.target.value)" type="text" placeholder="{{prov[col]}}">
</span>
<td>
<span *ngIf="editing && i === index">
<button (click)="save()">Save</button>
</span>
<span *ngIf="i !== index">
<button class="edit" name="editButton" (click)="editToggle(i); openEditForm()">/</button>
<button class="delete" (click)="deleteRow(i)">x</button>
</span>
</td>
</tr>
</table>
<!-- The EDITING Modal -->
<div id="editForm" class="modal_edit">
<div class="modal-content_edit">
<span (click)="save()" class="close">×</span>
<h2 style="margin-bottom: 70px">Edit OAuthAppProvider</h2>
<div>
<label style="margin-bottom: 20px">
Client Name:
</label>
<input [(ngModel)]="inputClientName" id="editClientName" type="text">
</div>
<div>
<label style="margin-bottom: 20px">
Version
</label>
<input id="editClientVersion" type="text">
</div>
<div>
<label style="margin-bottom: 20px">
API Key:
</label>
<input id="editClientAPIKey" type="text">
</div>
<div>
<label style="margin-bottom: 20px">
Protected Secret
</label>
<input id="editClientProtectedSecret" type="text">
</div>
<button style="float: right" class="add" (click)="save()">
<h4 style="font-style: bold">Save</h4>
</button>
<button class="cancel" (click)="save()">
<h4 style="font-style: bold">Cancel</h4>
</button>
</div>
</div>
</div>
export const PROVIDERS: any[] =
[
{
AppID: "11",
ClientName: "sampleclientname1",
apiKey: "sampleapikey1",
Version: "1.0",
protectedsecret: "samplesecret1"
},
{
AppID: "12",
ClientName: "sampleclientname2",
apiKey: "sampleapikey2",
Version: "1.0",
protectedsecret: "samplesecret2"
},
{
AppID: "13",
ClientName: "sampleclientname3",
apiKey: "sampleapikey3",
Version: "1.0",
protectedsecret: "samplesecret3"
},
{
AppID: "14",
ClientName: "sampleclientname4",
apiKey: "sampleapikey4",
Version: "1.0",
protectedsecret: "samplesecret4"
}
]
You can set a variable named something like selectedRowData and set the provider as its value when the user clicks the edit button. The value attribute of the inputs on the modal can be set to the properties of the selected row. It's difficult to tell what the functionality of the other methods is supposed to be without the component code so I made some assumptions. Let me know if you have any other questions about it.
Here's a link to a StackBlitz.
EDIT
The data is only being bound one way via the [value] attribute and there isn't a form object keeping track of all the changes like there would be using Reactive Forms so a model should be created first.
I commented out the original solution and added updates below. The selectedRowData variable is instantiated with a provider object with empty properties. The modal has been updated to use two-way binding with [(ngModel)]. The StackBlitz has also been updated.
The table is updated as the user types their edits into the form. The save button doesn't need to be used unless the data needs to be persisted somewhere.
Check out the Angular Forms Documentation it should help with how to pass form data around between components. What you've created here is similar to Template-driven Forms.
Component
// selectedRowData = null;
selectedRowData = {
AppID: "",
ClientName: "",
apiKey: "",
Version: "",
protectedsecret: ""
};
editToggle(rowData) {
this.selectedRowData = rowData;
}
Table
<div>
<table align="center">
<tr>
<th>
List of Providers
</th>
</tr>
</table>
<table id="thetable" align="center">
<tr>
<th>Application ID</th>
<th>Client Name</th>
<th>Version</th>
<th>API Key</th>
<th>Protected Secret</th>
<th>EDIT/DELETE</th>
</tr>
<tr ng-app="tblRowApp" *ngFor="let prov of providers; let i = index">
<td *ngFor="let col of columns">
<span class="field" *ngIf="i !== index">
{{prov[col]}}
</span>
<span *ngIf="i === index">
<input [(ngModel)]="inputClientName" class="table" value="{{prov[col]}}"
(change)="EditItem(value)" type="text" placeholder="{{prov[col]}}">
</span>
<td>
<span *ngIf="editing && i === index">
<button (click)="save()">Save</button>
</span>
<span *ngIf="i !== index">
<button class="edit" name="editButton" (click)="editToggle(prov); openEditForm()">/</button>
<button class="delete" (click)="deleteRow(i)">x</button>
</span>
</td>
</tr>
</table>
Modal
<!-- The EDITING Modal -->
<div id="editForm" class="modal_edit">
<div class="modal-content_edit">
<span (click)="save()" class="close">×</span>
<h2 style="margin-bottom: 70px">Edit OAuthAppProvider</h2>
<div>
<label style="margin-bottom: 20px">
Client Name:
</label>
<!-- <input id="editClientName" type="text" [value]="selectedRowData?.ClientName"> -->
<input id="editClientName" type="text" [(ngModel)]="selectedRowData.ClientName">
</div>
<div>
<label style="margin-bottom: 20px">
Version
</label>
<!-- <input id="editClientVersion" type="text" [value]="selectedRowData?.Version"> -->
<input id="editClientVersion" type="text" [(ngModel)]="selectedRowData.Version">
</div>
</div>
<div>
<label style="margin-bottom: 20px">
API Key:
</label>
<!-- <input id="editClientAPIKey" type="text" [value]="selectedRowData?.apiKey"> -->
<input id="editClientAPIKey" type="text" [(ngModel)]="selectedRowData.apiKey">
</div>
<div>
<label style="margin-bottom: 20px">
Protected Secret
</label>
<!-- <input id="editClientProtectedSecret" type="text" [value]="selectedRowData?.protectedsecret"> -->
<input id="editClientProtectedSecret" type="text" [(ngModel)]="selectedRowData.protectedsecret">
</div>
<button style="float: right" class="add" (click)="save()">
<h4 style="font-style: bold">Save</h4>
</button>
<button class="cancel" (click)="save()">
<h4 style="font-style: bold">Cancel</h4>
</button>
</div>
</div>
</div>
Hello there vue js guru's
Currently i'm creating some wizard with a little bit more "advanced" setup and need some help getting the correct outcome. I tried a few different methods but not with any success yet.
What i'm trying to do is the following:
I'm building a workout create wizard where it's possible to add sections and inside each section you could define one or more movements where each movement itself should have some sort of measurement this last one should change based on the selected movement and could have one or more options as an select to.
The data is fetched by axios (remotely) and saved to the data array for available movements like so:
[
'' => [
1 => [
'name' => 'pull ups',
'measure' => [
0 => 'none',
1 => 'distance',
],
],
2 => [
'name' => 'push ups',
'measure' => [
0 => 'none',
1 => 'weight',
],
],
...
],
...
]
this will then be stored in the this.movements = data.movements; data array in my vue js instance.
Here is my vue js code:
<script>
new Vue({
el: '#workout-wrapper',
data() {
return {
dynamicOptions: [],
name: null,
sections: [{
name: null,
rounds: null,
minutes: null,
measure: null,
movements: [{
reps: null,
movement: null,
measure: null,
remarks: null
}]
}],
movements: [],
...
}
},
methods: {
...
onMovementChange(group, movement) {
// TODO: this one combined with the computed options still isn't working correctly
if (group == '') {
this.options = { section: 0, movement: 0, options: this.movements[""][movement].measure };
} else {
this.options = { section: 0, movement: 0, options: this.movements[group][movement].measure };
}
},
...
},
computed: {
options: {
get(event, data) {
// TODO: now we should only return the options for section and movement indexes
return this.dynamicOptions;
},
set(data) {
this.dynamicOptions[data.section] = [];
this.dynamicOptions[data.section][data.movement] = data.options;
// console.log(this.dynamicOptions);
}
}
},
created() {
axios.get('/workouts/create/data').then(response => {
let data = response.data;
this.movements = data.movements;
...
}).catch(error => {
console.error(error);
});
}
});
</script>
And here the template:
<div class="row m-t-20" v-for="(section, index) in sections">
<div class="col-md-12">
<div class="card card-default no-border">
<div class="card-header separator">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Section name</label>
<div class="input-group m-b-15">
<input type="text" name="sections[0][name]" placeholder="e.g. Warming-Up" class="form-control" v-model="section.name">
<div class="input-group-btn">
<button type="button" class="btn btn-danger" data-title="Remove" data-tooltip #click="removeSection(index)">
<i class="fa fa-times"></i>
</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Rounds</label>
<input type="number" name="sections[0][rounds]" class="form-control" placeholder="Optional" min="0" v-model="section.rounds">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">
Minutes
</label>
<input type="number" name="sections[0][minutes]" class="form-control" placeholder="Optional" min="0" v-model="section.minutes">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Measure</label>
<select name="sections[0][measure]" class="form-control" v-model="section.measure"> {{-- data-init-plugin="select2" --}}
<option :value="key" v-for="(measure, key) in measurements">#{{ measure }}</option>
</select>
</div>
</div>
</div>
</div>
<div class="card-block m-t-25">
<table class="table table-striped">
<thead>
<tr>
<th width="10%">
Reps
</th>
<th width="35%">
Movement
</th>
<th width="20%">
Measure
</th>
<th width="35%">
Remarks
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(movement, movementIndex) in section.movements">
<td>
<input type="number" name="sections[0][movements][0][reps]" class="form-control" min="0" v-model="movement.reps">
</td>
<td>
<select name="sections[0][movements][0][movement]" class="form-control" v-model="movement.movement" #change="onMovementChange('', movement.movement)">
<optgroup :label="group" v-for="(options, group) in movements">
<option :value="key" v-for="(option, key) in options">#{{ option.name }}</option>
</optgroup>
</select>
</td>
<td>
<select name="sections[0][movements][0][measure]" class="form-control" v-model="movement.measure" :disabled="!movement.movement">
<option :value="key" v-for="(measure, key) in options">#{{ measure }}</option>
</select>
</td>
<td>
<textarea name="sections[0][movements][0][remark]" rows="1" class="form-control" v-model="movement.remarks"></textarea>
</td>
<td>
<button type="button" class="btn btn-link text-danger" data-title="Remove" data-tooltip #click="removeMovement(index, movementIndex)">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
<tr>
<td colspan="5" class="text-center">
<button type="button" class="btn btn-cons btn-complete" data-title="Add movement" data-tooltip #click="addMovement(index)">
<i class="fa fa-plus"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
With this current set up it's adding the data in the second select box but it's always changing, so when adding a second movement row then both select boxes are changing there options based on the selected movement in the second row etc... it should only change based on the current row instead and section off course.
Maybe some of you could help me with this problem... if more info is needed please let me know :-)
I am creating an alert component for a CRUD app using Vue.js. I want a message to be passed to another component once data has been saved. Currently I am trying to pass this data in $router.push like this this.$router.push({path: '/', query: {alert: 'Customer Added'}}) Then access this data in another component. However this is not working as expected, instead the data is passed into the url.
This is the component which saves the data, Add.vue
<template>
<div class="add container">
<Alert v-if="alert" v-bind:message="alert" />
<h1 class="page-header">Add Customer</h1>
<form v-on:submit="addCustomer">
<div class="well">
<h4>Customer Info</h4>
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" placeholder="First Name"
v-model="customer.first_name">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" placeholder="Last Name"
v-model="customer.last_name">
</div>
</div>
<div class="well">
<h4>Customer Contact</h4>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" placeholder="Email" v-model="customer.email">
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" placeholder="Phone" v-model="customer.phone">
</div>
</div>
<div class="well">
<h4>Customer Location</h4>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" placeholder="Address" v-model="customer.address">
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" placeholder="City" v-model="customer.city">
</div>
<div class="form-group">
<label>State</label>
<input type="text" class="form-control" placeholder="State" v-model="customer.state">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</template>
<script>
import Alert from './Alert'
export default {
name: 'add',
data () {
return {
customer: {},
alert:''
}
},
methods: {
addCustomer(e){
if(!this.customer.first_name || !this.customer.last_name ||
!this.customer.email){
this.alert = 'Please fill in all required fields';
} else {
let newCustomer = {
first_name: this.customer.first_name,
last_name: this.customer.last_name,
phone: this.customer.phone,
email: this.customer.email,
address: this.customer.address,
city: this.customer.city,
state: this.customer.state
}
this.$http.post('http://slimapp.dev/api/customer/add',
newCustomer)
.then(function(response){
this.$router.push({path: '/', query: {alert: 'Customer
Added'}})
});
e.preventDefault();
}
e.preventDefault();
}
},
components: {
Alert
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only
-->
<style scoped>
</style>
This the alert component, Alert.vue
<template>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></button>
{{message}}
</div>
</template>
<script>
export default {
name: 'alert',
props: ['message'],
data () {
return {
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
And this is the component where the alert is to be viewed, Customers.vue
<template>
<div class="customers container">
<Alert v-if="alert" v-bind:message="alert" />
<h1 class="page-header">Manage Customers</h1>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="customer in customers">
<td>{{customer.first_name}}</td>
<td>{{customer.last_name}}</td>
<td>{{customer.email}}</td>
<td></td></tr>
</tbody>
</table>
</div>
</template>
<script>
import Alert from './Alert';
export default {
name: 'customers',
data () {
return {
customers: [],
alert: ''
}
},
methods: {
fetchCustomers(){
this.$http.get('http://slimapp.dev/api/customers')
.then(function(response){
this.customers = (response.body);
});
}
},
created: function(){
if (this.$route.params.alert) {
this.alert = $route.params.alert
}
this.fetchCustomers();
},
updated: function(){
this.fetchCustomers();
},
components: {
Alert
}
}
How do I solve this?
It is not possible to pass data through vue-router the way you want to. You only can pass parameters like this:
Route definition:
{ path: '/products/:id/edit', name: 'products.edit', component: ProductForm },
And then you can get the parameter with this.$route.params.id
Or you can do:
this.$router.push({name: 'products.index', params: { id: 1 }})
I suggest you to add a GET parameter like ?success=true or show an alert with sweetalert for example before pushing the new route.
A weird solution is to set the value to store/local_storage and retrieve and destroy it from the store/local_storage when the destination page loads.
I am getting up the details in a form for a hotel entry with basic details and viewing it in Room.vue. The created values were displayed here but here i need to give edit option for the filled details. When i click the edit, the page should redirect to RoomsEdit.vue and i should get the filled up contents in that page with form inputs. For that i have tried the following codes but nothing solves my issue.. Kindly have a go through and help me in solving the issue.
Room.vue:
<table class="table table-striped table-hover rooms-table">
<thead>
<tr>
<td>Title<i class="fa fa-sort"></i></td>
<td>Sub Title<i class="fa fa-sort"></i></td>
<td> Edit </td>
<td> Delete </td>
</tr>
</thead>
<tbody>
<tr v-for="room in items">
<td>{{ room.title }}</td>
<td>{{ room.subtitle }}</td>
<td>
<router-link class="btn btn-primary" v-bind:to="'rooms/edit/'+id">Edit</router-link>
</td>
<td>
<button class="btn btn-primary" v-on:click="deleteRoom(room)">Delete</button>
</td>
</tr>
</tbody>
</table>
Here i am giving edit option and making a redirect to edit page..
Script of Rooms.vue:
<script>
import config from '../../../config';
export default {
data(){
return{
items: [],
itemsData:{
title : '',
subtitle : '',
}
}
},
methods: {
deleteRoom: function (room) {
var index = this.items.indexOf(room);
this.items.splice(index, 1);
}
},
mounted() {
axios.get(config.apiDomain+'/Rooms').then((response)=>this.items = response.data);
}
}
</script>
RoomsEdit.vue:
<form #submit.prevent="updateItems" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title<span class="red">*</span></label>
<div class="col-sm-6">
<input type="text" name="title" class="form-control" id="title" v-model="itemsData.title">
<span class="text-danger">{{ errors.title?errors.title[0]:"" }}</span>
</div>
</div>
<div class="form-group">
<label for="subtitle" class="col-sm-2 control-label">Subtitle<span class="red">*</span></label>
<div class="col-sm-6">
<input type="text" name="subtitle" class="form-control" id="subtitle" v-model="itemsData.subtitle">
<span class="text-danger">{{ errors.subtitle?errors.subtitle[0]:"" }}</span>
</div>
</div>
</form>
Script of RoomsEdit:
<script>
import config from '../../../config';
export default {
data(){
return{
items: [],
itemsData:{
title : '',
subtitle : '',
},
errors: {
}
}
},
methods:{
fetchRoom(id){
axios.get(config.apiDomain+'/Rooms').then((response)=>this.items = response.data);
},
updateItems(e){
axios.put(config.apiDomain+'/Rooms/edit'+this.$route.params.id,this.itemsData).then(response=>{
this.this.itemsData = "";
this.$router.push('/admin/rooms');
}).catch(error=>{
this.errors = error.response.data;
});
}
},
created: function() {
this.fetchRoom(this.$route.params.id);
}
}
</script>
RoomsCreate.vue:
<form #submit.prevent="addItems" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title<span class="red">*</span></label>
<div class="col-sm-6">
<input type="text" name="title" class="form-control" id="title" v-model="itemsData.title">
<span class="text-danger">{{ errors.title?errors.title[0]:"" }}</span>
</div>
</div>
<div class="form-group">
<label for="subtitle" class="col-sm-2 control-label">Subtitle<span class="red">*</span></label>
<div class="col-sm-6">
<input type="text" name="subtitle" class="form-control" id="subtitle" v-model="itemsData.subtitle">
<span class="text-danger">{{ errors.subtitle?errors.subtitle[0]:"" }}</span>
</div>
</div>
Script of RoomsCreate.vue:
<script>
import config from '../../../config';
export default {
data(){
return{
items: [],
itemsData:{
title : '',
subtitle : '',
},
errors: {
}
}
},
methods:{
addItems(){
axios.post(config.apiDomain+'/Rooms',this.itemsData).then(response=>{
this.this.itemsData = "";
this.$router.push('/admin/rooms');
}).catch(error=>{
this.errors = error.response.data;
});
}
}
</script>
The issue i am facing is when i click the edit in Room.vue, it redirects to the RoomsEdit.vue where i am not getting the values that was already created, i need to get those value when i go to RoomsEdit.vue there i should edit and update the content.