Vue router get value from vue router link - javascript

I have a list here from my table. It has a edit button and if I click edit button, It goes to another component which is called editTeacher. My question is how could I get the data from the table and transfer it to my editTeacher component. I get the data from route using axios . In laravel it is like this
<span class="glyphicon glyphicon-pencil"> .
How could I achieve it in vue?
Here is my code snippet
<table id="myTable" class="table table-hover">
<tbody>
<tr>
<th>ID</th>
<th>Image</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Birthday</th>
<th>Age</th>
<th>Type</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
<tr v-for="teacher in teachers" :key="teacher.id">
<td>{{teacher.id}}</td>
<td><img style=" border-radius: 50%;" :src="'img/'+teacher.image" height="42" width="42"/></td>
<td>{{teacher.firstname}}</td>
<td>{{teacher.lastname}}</td>
<td>{{teacher.gender}}</td>
<td>{{teacher.birthday}}</td>
<td>{{teacher.age}}</td>
<td>{{teacher.type}}</td>
<td>{{teacher.department_name}}</td>
<td v-if="teacher.status == 1"><span class="label label-success">Active</span></td>
<td v-else><span class="label label-danger">Inactive</span></td>
<td><router-link to="/viewTeacher"> <i class="fa fa-edit"></i></router-link></td>
</tr>
</tbody>
</table>
Route
//Teachers
Route::get('/getTeachers','TeacherController#index');
Route::post('/addTeacher','TeacherController#store');
Route::put('/editTeacher/{id}','TeacherController#update');
app.js route
{ path: '/viewTeacher', component: require('./components/editTeacher.vue').default },

Please follow the below code for the Vue js edit method.
As per your git repo.
app.js route
{ path: '/viewTeacher/:id', component: require('./components/editTeacher.vue').default, name: viewTeacher},
Edit Button in Teachers.vue
<router-link :to="{name: 'viewTeacher', params: {id: teacher.id}}" class="btn btn-xs btn-default">Edit</router-link>
EditTeacher.vue component
<template>
<div class="row">
<div class="col-xs-3">
<div class="box">
<div class="box-tools">
<img style="border-radius: 50%;" src="" height="100" width="50">
</div>
</div>
</div>
<div class="col-xs-9">
<div class="box">
<form v-on:submit.prevent="saveForm()">
<div class="row">
<div class="col-xs-12 form-group">
<label class="control-label">Teacher first name</label>
<input type="text" v-model="teacher.firstname" class="form-control">
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
<label class="control-label">Teacher Last name</label>
<input type="text" v-model="teacher.lastname" class="form-control">
</div>
</div>
<div class="row">
<div class="col-xs-12 form-group">
<button class="btn btn-success">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.teacherId = id;
axios.get('/getTeacher/' + id)
.then(function (resp) {
app.teacher = resp.data;
})
.catch(function () {
alert("Could not load teacher")
});
},
data: function () {
return {
teacherId: null,
teacher: {
firstname: '',
lastname: '',
}
}
},
methods: {
saveForm() {
var app = this;
var newTeacher = app.teacher;
axios.patch('/editTeacher/' + app.teacherId, newTeacher )
.then(function (resp) {
app.$router.replace('/');
})
.catch(function (resp) {
console.log(resp);
alert("Could not Update");
});
}
}
}
Web.php
Route::get('/getTeachers','TeacherController#index');
Route::get('/getTeacher/{id}','TeacherController#show');
Route::post('/addTeacher','TeacherController#store');
Route::put('/editTeacher/{id}','TeacherController#update');
Controller
public function show($id)
{
return Teacher::findOrFail($id);
}

Related

List.js apply filter by default

I am a beginner in Javascript and would appreciate some guidance in using the List.js library. So far, I have created the filters and they are able to work. But I would like the default table to have filter 'Pending Delivery' applied already as this would be the most commonly accessed page.
HTML
(There is already code for the filters)
<table class="order-table table table-hover table-striped">
<thead>
<th>S/N</th>
<th>Order ID</th>
<th>Customer Name</th>
<th>Route Number</th>
<th>Order Date</th>
<th>Delivery Date</th>
<th>Status</th>
</thead>
<tbody class="list">
<tr>
<td>1</td>
<td class='orderId'>5</td>
<td>Matilda Tan</td>
<td>16</td>
<td>2018-06-29</td>
<td>2018-06-29</td>
<td class='sts'>Pending Delivery</td>
</tr>
<tr>
<td>2</td>
<td class='orderId'>7</td>
<td>Xena Yee</td>
<td>01</td>
<td>2018-06-21</td>
<td>2018-06-23</td>
<td class='sts'>Delivered</td>
</tr>
<div class="no-result">No Results</div>
<ul class="pagination"></ul>
</div>
</div>
</div>
JS
var options = {
valueNames: [
'name',
'sts',
{ data: ['status']}
],
page: 5,
pagination: true
};
var userList = new List('users', options);
function resetList(){
userList.search();
userList.filter();
userList.update();
$(".filter-all").prop('checked', true);
$('.filter').prop('checked', false);
$('.search').val('');
//console.log('Reset Successfully!');
};
function updateList(){
var values_status = $("input[name=status]:checked").val();
console.log(values_status);
userList.filter(function (item) {
var statusFilter = false;
if(values_status == "All")
{
statusFilter = true;
} else {
statusFilter = item.values().sts == values_status;
}
return statusFilter
});
userList.update();
//console.log('Filtered: ' + values_gender);
}
$(function(){
//updateList();
$("input[name=status]").change(updateList);
userList.on('updated', function (list) {
if (list.matchingItems.length > 0) {
$('.no-result').hide()
} else {
$('.no-result').show()
}
});
});
You have duplicated IDs. That's an error because an ID must be unique.
If you need to change from All to Pending Delivery selected it is enough to change your html moving the checked attribute from current position (All) to the Pending Delivery position.
After, call your updateList(); after the $("input[name=status]").change(updateList); in your dom ready function.
Your updated codepen
The short changes in your code:
$(function(){
//updateList();
$("input[name=status]").change(updateList);
updateList(); // this line added
userList.on('updated', function (list) {
if (list.matchingItems.length > 0) {
$('.no-result').hide()
} else {
$('.no-result').show()
}
});
});
<div class="container">
<div class="row">
<div id="users" class="col-xs-12">
<div class="filter-group row">
<div class="form-group col-xs-12 col-sm-12 col-md-4">
<input type="text" class="search form-control" placeholder="Search" />
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-4">
<div class="radio-inline">
<label>
<input class="filter-all" type="radio" value="All"
name="status" id="status-all"/> All <!-- removed checked -->
</label>
</div>
<div class="radio-inline">
<label>
<input class="filter" type="radio"
value="Pending Delivery" name="status" id="status-pending" checked/>
Pending <!-- added checked -->
</label>
</div>
.......

show div on selection ajax and laravel

I have two div on index page that contains a datatable i need to hide two div by default when I select an option in dropdown then i need to show that corresponding div based on selection.
I am using this page for searching a div contains a drop downmenu contains two options to select.when i select indents it should return that corresponding div
Index File
#include('theme.header')
<br>
<div class="row" id="dropsearch">
<div class="col-12">
<div class="card m-b-30">
<div class="card-body ">
<h4 class="mt-0 header-title">Search Indent</h4>
<label class="pull-left">
<select class="pull-left form-control input-lg" id="dropsearch" name="dropsearch">
<option>Select Search</option>
<option>Indents</option>
<option>Jobcards</option>
</select>
</label>
</div>
</div>
</div>
</div>
<div class="row" id="indents">
<div class="col-12">
<div class="card m-b-30">
<div class="card-body ">
<h4 class="mt-0 header-title">Search Indent</h4>
<input type="text" id="searchid" name="searchid" class="pull-right form-control-sm">
<label class="pull-right">search</label>
<br>
<br><br>
<table id="datatable" class="table table-bordered table-responsive-lg">
<thead>
<tr>
<th>Slno</th>
<th>Customer Name</th>
<th>Customer Phone Number</th>
<th>DateOfDelivery</th>
<th>Delivery At</th>
<th>Redistraion Mode</th>
<th>Chassis No</th>
<th>Engine No</th>
<th>Show</th>
</tr>
</thead>
<tbody id="searchinfo">
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br>
<br>
<div class="row" id="jobcardd">
<div class="col-12">
<div class="card m-b-30">
<div class="card-body bg-secondary text-white">
<h4 class="mt-0 header-title">Search Jobcard</h4>
<input type="text" id="searchjob" name="searchjob" class="pull-right form-control-sm">
<label class="pull-right">search</label>
<br>
<br><br>
<table id="datatable" class="table table-bordered table-responsive-lg">
<thead>
<tr>
<th>Slno</th>
<th>Jobcard No</th>
<th>Customer Order No</th>
<th>Ticket No</th>
<th>Bill No</th>
<th>Show</th>
</tr>
</thead>
<tbody id="searchjobcard">
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
$('#indents').hide();
$('#jobcardd').hide();
$(function () {
$("#dropsearch").change(function () {
if ($(this).val() == "indents") {
$("#indents").show();
}
else if ($(this).val() == "jobcard") {
$("#jobcardd").show();
}
});
});
$(document).ready(function () {
$('#searchid').on('keypress', function () {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('searchindents')}}',
data: {'searchid': $value},
success: function (data) {
$('#searchinfo').html(data);
// console.log(data);
}
})
})
});
$(document).ready(function () {
$('#searchjob').on('keypress', function () {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('searchjobacard')}}',
data: {'searchjob': $value},
success: function (data) {
$('#searchjobcard').html(data);
// console.log(data);
}
})
})
});
</script>
<script>
$.ajaxSetup({headers: {'csrftoken': '{{ csrf_token() }}'}});
</script>
#include('theme.footer')
Change this
<option>Select Search</option>
<option>Indents</option>
<option>Jobcards</option>
To this
<option value="">Select Search</option>
<option value="indents">Indents</option>
<option value="jobcard">Jobcards</option>
Update
You have given same ID to the DIV and DropDown!!
Use this
<select class="pull-left form-control input-lg" id="dropsearchselect" name="dropsearch">
<option value="">Select Search</option>
<option value="indents">Indents</option>
<option value="jobcard">Jobcards</option>
</select>
$(function () {
$("#dropsearchselect").change(function () {
if ($(this).val() == "indents") {
$("#indents").show();
}
else if ($(this).val() == "jobcard") {
$("#jobcardd").show();
}
});
});
Here is a fiddle
Update 2
$('#indents').hide();
$('#jobcardd').hide();
$(function () {
$("#dropsearchselect").change(function () {
if ($(this).val() == "indents") {
$('#jobcardd').hide();
$("#indents").show();
}
else if ($(this).val() == "jobcard") {
$('#indents').hide();
$("#jobcardd").show();
}else{
$('#indents').hide();
$('#jobcardd').hide();
}
});
});

Manipulate table in knockout.js

I am consuming api successfully in knockout.js.But according to my table definition(id,name,debit,credit,amount),this is based on accounting.The amount i want to show if it is credit or debit since not all the amount are under the debit and credit the same time.kindly help me to diplay the amount under redit and debit respectively.
This is the viewmodel
function JournalViewModel() {
var self = this;
self.Period = ko.observable();
self.PayGroup = ko.observable();
self.PayGroups = ko.observableArray([]);
self.LoadPeriods = function () {
$.ajax({
url: baseUrl + 'api/Process/Load',
type: 'GET',
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: 'json',
success: function (data) {
console.log(data);
if (data.Successfull == 1) {
self.Period(data.Model.CurrentPeriod);
self.PayGroups(data.Model.Paygroups);
}
},
error: function (request, error) {
console.log(error);
}
});
}
self.periodId = ko.observable();
self.PaygroupId = ko.observable();
self.Journal = ko.observableArray([]);
self.PayMaster = ko.observableArray();
self.LoadJournal = function () {
$.ajax({
url: baseUrl + 'api/Journal/LoadJournal/'+periodId +'/'+self.PaygroupId(),
type: 'GET',
cache: false,
headers: { 'Access-Control-Allow-Origin': '*' },
dataType: 'json',
success: function (data) {
if (data.HasError == 0) {
self.Journal(data.Model);
console.log(data.Model);
alert("Journal Successfully Processed");
$("#listTable").DataTable();
}
},
error: function (request, error) {
console.log(error);
}
});
}
self.StartDate = ko.observable()
self.EndDate = ko.observable()
self.NbDays = ko.observable();
self.NbHours = ko.observable();
self.Code = ko.observable();
self.CountEmployees = ko.observable();
self.LoadPeriods();
}ko.applyBindings(new JournalViewModel());
this is my view
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<nav role="navigation" aria-labelledby="system-breadcrumb">
<ol class="breadcrumb">
<li>Process</li>
<li>Journals</li>
</ol>
</nav>
<div class="box box-primary">
<div class="box-body">
<div class="col-md-12">
<div class="col-md-2">
<div class="form-group">
<label for="PeriodTxt">Pay Group</label>
<select data-bind="options: PayGroups,
optionsText: 'Name',
optionsValue: 'Id',
optionsCaption: 'Choose...',
value:PaygroupId" class="form-control"></select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="PeriodTxt">Period</label>
<input id="FullNameTxt" class="form-control" type="text"
readonly="readonly"
data-bind="value:Period()?Period().Code:''" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="StatusTxt">Number of Hours</label>
<input id="StatusTxt" class="form-control" type="text"
readonly="readonly"
data-bind="value:Period()?Period().NbHours:''" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="ds"></label>
<input type="submit" value="Load Journal" data-
bind="click:LoadJournal" class="btn btn-primary btn-block" />
</div>
</div>
</div>
</div>
</div>
<div class="well">
<div class="well-body">
<table id="listTable" class='table table-striped table-bordered'>
<thead>
<tr>
<th>
Account Code
</th>
<th>
Name
</th>
<th>
Debit
</th>
<th>
Credit
</th>
</tr>
</thead>
<tbody data-bind="foreach:Journal">
<tr>
<td data-bind="text:AcctId">
</td>
<td data-bind="text:AcctDescription">
</td>
<!-- ko if:Debit==1 -->
<td data-bind="text:Amount">
</td>
<!-- /ko -->
<!-- ko if:Credit==1 -->
<td data-bind="text:Amount"></td>
<!-- /ko -->
</tr>
</tbody>
</table>
</div>
</div>
#section Scripts{
<script>periodId = '#ViewBag.PeriodId';</script>
}
The problem is that you have the if condition on the tag, which will not render if false. The trick is to put it inside the tag as you want that to be shown all the time, just not the value inside. (If I understood your question correctly ofcourse)
<table>
<thead>
<tr>
<th>Account Code</th>
<th>Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="text:AcctId"></td>
<td data-bind="text:AcctDescription"></td>
<td>
<span data-bind="if: Debit == 1">
<!-- ko text: Amount -->
<!-- /ko -->
</span>
</td>
<td>
<span data-bind="if: Credit == 1">
<!-- ko text: Amount -->
<!-- /ko -->
</span>
</td>
</tr>
</tbody>
</table>

What causes VueJS to stop updating the DOM in this instance?

I've looked on every similar post that I can find, but no answer seems to fix my issue. Specifically, it does not update the table with id "table".
HTML:
<section id="body">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-primary">
<div class="panel-heading" id="panel">
<div class="row">
<div class="col-sm-12">
<h3 class="panel-title">Filters</h3>
</div>
</div>
</div>
<div class="panel-body" id="panel-body">
<div class="row">
<div class="col-sm-12">
<form id="filterForm" class="form-horizontal">
<div class="form-group">
<div class="col-sm-12">
<label class="control-label" for="focusedInput">Category:</label>
<select id="category" class="js-example-basic-single form-control">
<option value="">Any</option>
<option v-for="category in categories" value="category.categoryTitle">
{{category.categoryTitle}}</option>
</select>
</div>
</div>
<div class="form-inline row">
<div class="col-sm-12">
<label class="control-label" style="margin-right:20px;">Air Date:</label>
<div style="width:35%" class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" v-model="airDate"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<label class="control-label">Show Number:</label>
<input style="width:35%" class="form-control" type="number" id="showNumber" v-model="showNumber">
</div>
</div>
<div class="form-inline row">
<div class="col-sm-12">
<label class="control-label">Question contains:</label>
<input style="width:35%" class="form-control" type="text" v-model="questionText">
<label class="control-label">Dollar Value:</label>
<input style="width:35%" class="form-control" type="number" id="showNumber" v-model="dollarValue">
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-offset-9 col-sm-3" style="margin-top:5px;">
<button type="button" class="btn btn-warning" v-on:click="reset">Reset Filters</button>
<button type="button" class="btn btn-primary" v-on:click="filter">Filter</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="panel panel-primary" id="tableCard" style="margin-bottom:20px; margin-top:40px;">
<div class="panel-heading">
<div class="row">
<div class="col-sm-10">
<h3 class="panel-title">Jeopardy Questions</h3>
</div>
<div class="col-sm-2">
<span id="totalQuestionsSpan">Total Entries: {{entries.length}} entries</span>
</div>
</div>
</div>
<div class="panel-body" style="padding-top:45px;">
<div class="wrapper">
<table id="tableScroll" class="table table-striped table-fixed">
<thead style="background-color:white;">
<tr>
<th style="cursor:pointer; min-width: 110px;">
Question
<span v-if="questionSort == 1" id="questionUp">▲</span>
<span v-else-if="questionDown == -1" id="questionDown">▼</span>
</th>
<th style="cursor:pointer; min-width: 120px; ">
Answer
<span v-if="answerSort == 1" id="answerUp">▲</span>
<span v-else-if="answerDown == -1" id="answerDown">▼</span>
</th>
<th style="cursor:pointer; min-width: 80px;">
Value
<span v-if="valueSort == 1" id="valueUp">▲</span>
<span v-else-if="valueDown == -1" id="valueDown">▼</span>
</th>
<th style="cursor:pointer; min-width: 80px;">
Show Number
<span v-if="showNumberSort == 1" id="showNumberUp">▲</span>
<span v-else-if="showNumberDown == -1" id="showNumberDown">▼</span>
</th>
<th style="cursor:pointer; min-width: 80px;">
Category
<span v-if="categorySort == 1" id="categoryUp">▲</span>
<span v-else-if="categoryDown == -1" id="categoryDown">▼</span>
</th>
<th style="cursor:pointer; min-width: 80px;">
Air Date
<span v-if="airDateSort == 1" id="airDateUp">▲</span>
<span v-else-if="airDateDown == -1" id="airDateDown">▼</span>
</th>
</tr>
</thead>
<tbody id="table">
<tr v-for="entry in entries">
<td>{{entry.questionText}}</td>
<td>{{entry.answerText}}</td>
<td>{{entry.dollarValue}}</td>
<td>{{entry.showNumber}}</td>
<td>{{entry.categoryTitle}}</td>
<td>{{entry.airDate}}</td>
</tr>
<tr v-if="entries.length == 0">
<td colspan="6" style="text-align: center;"> No entries to display </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
JS
var app = new Vue({
el: '#body',
data: {
loggedIn: false,
questionSort: 0,
answerSort: 0,
valueSort: 0,
showNumberSort: 0,
categorySort: 0,
airDateSort: 0,
entries: [],
url: "/questions",
categories: [],
// form model data
categoryTitle: '',
airDate: '',
questionText: '',
dollarValue: '',
showNumber: '',
},
mounted: function () {
$.get("/api/categories", function(result) {
Vue.set(app, "categories", result.data);
$('.js-example-basic-single').select2();
}, "json").fail(function(err) {
showErrorMessage(err.responseJSON.message_prettified);
});
},
methods: {
filter : function() {
var queryParams = "?";
var params = 0;
app.categoryTitle = $('#category :selected').text().trim();
if (typeof app.categoryTitle !== "undefined" && app.categoryTitle != null) {
params++;
queryParams += "categoryTitle=" + app.categoryTitle
}
if (app.airDate.length > 0) {
params++;
if (params > 0) {
queryParams += "&";
}
queryParams += "airDate=" + app.airDate
}
if (app.questionText.length > 0) {
params++;
if (params > 0) {
queryParams += "&";
}
queryParams += "questionText=" + app.questionText
}
if (app.dollarValue.length > 0) {
params++;
if (params > 0) {
queryParams += "&";
}
queryParams += "dollarValue=" + app.dollarValue
}
if (app.showNumber.length > 0) {
params++;
if (params > 0) {
queryParams += "&";
}
queryParams += "showNumber=" + app.showNumber
}
if (queryParams.length == 1) {
queryParams = "";
}
var url = "/questions"
var URL = url + queryParams;
$.get(URL, result => {
Vue.set(app, "entries", result.data);
app.$forceUpdate();
}, "json").fail(function(err) {
showErrorMessage(err.responseJSON.message_prettified);
}).always(function() {
$("#loader").addClass("toggled");
});
}
}
});
Current behavior:
The AJAX call to /api/categories correctly updates the dropdown on the DOM, allowing me to select a category. When the app is mounted, it does update the table, showing the colspan 6 "No entries to display" cell. However, after the filter request is sent and returns, the table does not update to reflect the updated data (despite the data correctly showing as having been changed when checked in the console).
Expected behavior:
When the AJAX call to /questions with the query params resolves and updates the entries data field in app, the table updates to reflect the changes.
Attempted fixes:
Explored $forceUpdate, $set, Vue.set, and manually overwriting the array using a for loop.
Edit:
After doing a lot of snooping and also integrating VueX (as suggested below by #WaldemarIce) which may have helped but regardless did improve the overall code structure of my mini program, I've arrived to a solution.
This post on Laracast made me wonder whether perhaps there was a data issue: https://laracasts.com/discuss/channels/vue/v-for-loop-rendering-keeps-throwing-undefined-error
Which then caused me to realize the problem was in this line of code here:
<option v-for="category in categories" value="category.categoryTitle">
{{category.categoryTitle}}</option>
Which was causing an issue because category in value="category.categoryTitle" wasn't defined until later in the life cycle. I changed that to v-bind:value="category.categoryTitle" and updated my JS to make it work now. The TypeError that I posted in the follow-up discussions on #Kaicui 's post was causing Vue to lose the reactivity of the data. Once I solved that problem, Vue began to react properly again.
Updated HTML:
<section id="body">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-primary">
<div class="panel-heading" id="panel">
<div class="row">
<div class="col-sm-11">
<h3 class="panel-title">Filters</h3>
</div>
<div class="col-sm-1">
<i id="toggleFilter" class="fa fa-chevron-down filter-collapsed" style="cursor:pointer; display:none;" aria-hidden="true"></i>
<i id="toggleFilter" class="fa fa-chevron-up filter-collapsed" aria-hidden="true" style="cursor:pointer;"></i>
</div>
</div>
</div>
<div class="panel-body" id="panel-body">
<div class="row">
<div class="col-sm-12">
<form id="filterForm" method="GET" action="/questions" class="form-horizontal">
<div class="form-inline">
<div class="col-sm-12" style="margin-bottom:15px;">
<input type="hidden" name="categoryTitle" id="categoryTitleHidden">
<label class="control-label" for="focusedInput">Category:</label>
<select style="width:90%; height:120% !important;" v-model="categorySelect" id="category" class="js-example-basic-single form-control">
<option value="">Any</option>
<option v-for="category in categories" v-bind:value="category.categoryTitle">
{{category.categoryTitle}}</option>
</select>
</div>
</div>
<div class="form-inline">
<div class="col-sm-12" style="margin-bottom:15px;">
<label class="control-label" style="margin-right:20px;">Air Date:</label>
<div style="width:35%; margin-right:10px" class="form-group">
<div style="width:100%" class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" name="airDate"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<label class="control-label">Show Number:</label>
<input style="width:35%" class="form-control" type="number" id="showNumber" name="showNumber">
</div>
</div>
<div class="form-inline">
<div class="col-sm-12">
<label class="control-label">Question contains:</label>
<input style="width:35%" class="form-control" type="text" id="questionText" name="questionText">
<label class="control-label">Dollar Value:</label>
<input style="width:35%" class="form-control" type="number" id="dollarValue" name="dollarValue">
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-offset-9 col-sm-3" style="margin-top:5px;">
<button type="button" class="btn btn-warning" v-on:click="reset">Reset Filters</button>
<button type="button" class="btn btn-primary" v-on:click="filter">Filter</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="panel panel-primary" id="tableCard" style="margin-bottom:20px; margin-top:40px;">
<div class="panel-heading">
<div class="row">
<div class="col-sm-10">
<h3 class="panel-title">Jeopardy Questions</h3>
</div>
<div class="col-sm-2">
<span id="totalQuestionsSpan">Total Entries: {{entryCount}} entries</span>
</div>
</div>
</div>
<div class="panel-body" style="padding-top:45px;">
<div class="wrapper">
<table id="tableScroll" class="table table-striped table-fixed">
<thead style="background-color:white;">
<tr>
<th style="cursor:pointer; min-width: 110px;">
Question
</th>
<th style="cursor:pointer; min-width: 120px; ">
Answer
</th>
<th style="cursor:pointer; min-width: 80px;">
Value
</th>
<th style="cursor:pointer; min-width: 80px;">
Show Number
</th>
<th style="cursor:pointer; min-width: 80px;">
Category
</th>
<th style="cursor:pointer; min-width: 80px;">
Air Date
</th>
</tr>
</thead>
<tbody id="table">
<tr v-if="entriesValid" v-for="entry in entries">
<td>{{entry.questionText}}</td>
<td>{{entry.answerText}}</td>
<td>{{entry.dollarValue}}</td>
<td>{{entry.showNumber}}</td>
<td>{{entry.categoryTitle}}</td>
<td>{{entry.airDate}}</td>
</tr>
<tr v-if="!entriesValid">
<td colspan="6" style="text-align: center;"> No entries to display </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="position: absolute; left: 45%; top:25%; z-index:3;">
<i id="loader" class="fa fa-circle-o-notch fa-spin fa-5x fa-fw toggled" style="z-index:3"></i>
</div>
</section>
Updated JS
Vue.use(Vuex)
Vue.config.debug = false;
Vue.config.silent = true;
var URL;
const store = new Vuex.Store({
state: {
loggedIn: false,
// ordering data
questionSort: 0,
answerSort: 0,
valueSort: 0,
showNumberSort: 0,
categorySort: 0,
airDateSort: 0,
// server related ata
entries: [],
url: "/questions",
categories: [{
categoryTitle: "Test",
}],
},
mutations: {
categories (state, data) {
state.categories = data;
},
entries (state, data) {
console.log(data);
state.entries = data;
console.log(state.entries)
}
},
actions: {
fetchCategories ({ commit }) {
$("#loader").removeClass("toggled");
$.get("/api/categories", function(result) {
commit('categories', result.data);
}, "json")
.fail(function(err) {
if (err.status == 0) {
showErrorMessage("Network Problem");
}
else {
showErrorMessage(err.responseJSON.message_prettified);
}
}).always(function() {
$("#loader").addClass("toggled");
});
},
},
});
var app = new Vue({
el: '#body',
store: store,
data: {
categorySelect: "",
},
mounted: function() {
store.dispatch("fetchCategories").then(() => {
$('.js-example-basic-single').select2();
});
},
computed: {
categories: function() {
return store.state.categories;
},
entryCount: function() {
if (store.entries) {
if (typeof store.entries.length !== "undefined") {
return store.entries.length;
}
else {
return 0;
}
}
else {
return 0;
}
},
entriesValid: function() {
if (store.state.entries) {
if (typeof store.state.entries.length !== "undefined" && store.state.entries.length > 0) {
return true;
}
else {
return false;
}
}
else {
return false;
}
},
entries: function() {
return store.state.entries;
},
loggedIn: function() {
return store.state.loggedIn;
},
},
methods: {
reset: function() {
$('.js-example-basic-single').val('').trigger('change');
$("#datetimepicker1").datetimepicker("clear");
$("#categoryTitleHidden").val("");
$("#showNumber").val("");
$("#questionText").val("");
$("#showNumber").val("");
$("#dollarValue").val("");
},
filter : function() {
var value = $('#category :selected').text().trim();
if (value !== "Any") {
$("#categoryTitleHidden").val(value);
}
else {
$("#categoryTitleHidden").val("");
}
var options = {
success: function(responseText, statusText, xhr, $form) {
store.commit("entries", JSON.parse(xhr.responseText).data)
}
};
$("#filterForm").ajaxSubmit(options);
}
}
});
IMO problem is causing Vue.set(app, ...). AFAIK you can't set properties on Vue instance itself.
EDIT: Live example with Vuex and async data with jQuery
var store = new Vuex.Store({
state: {
// Car manufacturers for datalist will be held here.
// Cars are globally accessible, in every component,
// as this.$store.state.cars
cars: null
},
mutations: {
// Mutations changes state, but must be sync,
// so you can't call $.get() or another
// async function in any mutation.
updateCars: function (state, payload) {
state.cars = payload
}
},
actions: {
// For async ops there are actions,
// but they can't change state - for state
// change fire particular mutation.
loadCars: function (context, payload) {
$.get(payload.src).then(function (data) {
context.commit('updateCars', data)
})
}
}
})
Vue.component('my-list', {
template: '#my-list',
props: ['src'],
// All components see this.$store.state.cars, but
// still can have own local data.
data: function () {
return {
manufacturer: ''
}
},
// Fire async store action
created: function () {
this.$store.dispatch({
type: 'loadCars',
src: this.src
})
}
// Alternatively, you can use this
// version - w/o action. It's OK to use
// mutation here, in callback of async function.
/* created: function () {
$.get(this.src).then(function (data) {
this.$store.commit('updateCars', data)
})
} */
})
new Vue({
el: '#app',
// Inject store state to all components
store: store
})
<div id="app">
<my-list src="https://api.mockaroo.com/api/32318a80?count=20&key=cdbbbcd0">
</my-list>
</div>
<template id="my-list">
<div>
<label>
Choose a car manufacturer:<br>
<input list="cars" name="myCars" v-model="manufacturer">
</label>
<datalist id="cars">
<option
v-for="car in $store.state.cars"
:value="car.car"
>
{{ car.id }}
</option>
</datalist>
<p>
Selected manufacturer:<br>
{{ manufacturer }}
</p>
</div>
</template>
<script src="https://unpkg.com/vue#2.5.2/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex#3.0.0/dist/vuex.min.js"></script>
<script src="https://unpkg.com/jquery#3.2.1/dist/jquery.min.js"></script>
your code can not run because it relies on your server response.
but i think your code which setting resonse data to entries is fine.
This kind of problems may occur when other js code have caused an exception ,which interrupt the rendering of vue.
so could you check console and see is there any errors?

How to edit and update form input values in vue.js?

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.

Categories