I'm trying to reload the page after save in laravel and vue.js, I do this in "fetchGoals". Here is what I've tried and it works the first time, it saves the goal and refreshes the page. When I try to add another goal then the save button no longer works and the page will not refresh. Same goes for the edit button, it will work the first time and then the second time it will not. Regardless if is save or edit, the same problem exists where I can only perform one function where the pages refreshes. Any ideas what I'm doing wrong?
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<form #submit.prevent="addGoal" class="mb-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="Goal" v-model="goal.title">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Description" v-model="goal.description">
</textarea>
</div>
<button type="submit" class="btn btn-primary btn-block">Add New Goal</button>
</form>
<button #click="clearForm()" class="btn btn-danger btn-block">Cancel</button>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr v-for="goal in goals" v-bind:key="goal.id">
<td>{{goal.id}}</td>
<td>{{goal.title}}</td>
<td>{{goal.description}}</td>
<td>
<button #click="editGoal(goal)" class="btn btn-warning btn-xs">Edit</button>
</td>
<td>
<button #click="deleteGoal(goal.id)" class="btn btn-danger btn-xs">Delete
</button>
</td>
</tr>
</tbody>
</table>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li v-bind:class="[{disabled: !pagination.prev_page_url}]" class="page-item">
<a class="page-link" href="#" #click="fetchGoals(pagination.prev_page_url)">Previous</a>
</li>
<li class="page-item disabled">
<a class="page-link text-dark" href="#">Page {{ pagination.current_page }} of {{
pagination.last_page }}</a>
</li>
<li v-bind:class="[{disabled: !pagination.next_page_url}]" class="page-item">
<a class="page-link" href="#"
#click="fetchGoals(pagination.next_page_url)">Next</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
goals: [],
goal: {
id: '',
title: '',
description: '',
user_id: 1,
},
goal_id: '',
pagination: {},
edit: false
};
},
created() {
this.fetchGoals();
},
methods: {
//gets the data and the pagination
fetchGoals(page_url) {
let vm = this;
page_url = page_url || '/api/goals';
fetch(page_url)
.then(res => res.json())
.then(res => {
this.goals = res.data;
//this comes from res and res is the data from the Jason
vm.makePagination(res.meta, res.links);
})
.catch(err => console.log(err));
},
addGoal() {
if (this.edit === false) {
// Add
fetch(`/api/goal`, {
method: 'post',
body: JSON.stringify(this.goal),
headers: {
'content-type': 'application/json',
}
})
.then(res => res.json())
.then(data => {
this.clearForm();
alert('Article Added');
this.fetchGoals();
})
.catch(err => console.log(err));
} else {
//Edit save
fetch(`/api/goal`, {
method: 'put',
body: JSON.stringify(this.goal),
headers: {
'content-type': 'application/json',
}
})
.then(res => res.json())
.then(data => {
this.clearForm();
alert('Article Added');
this.fetchGoals();
})
.catch(err => console.log(err));
}
},
editGoal(goal) {
this.edit = true;
this.goal.id = goal.id;
this.goal.goal_id = goal.id;
this.goal.title = goal.title;
this.goal.description = goal.description;
},
clearForm() {
this.edit = false;
this.goal.id = null;
this.goal.goal_id = null;
this.goal.title = '';
this.goal.description = '';
this.goal.user_id = null;
}
}
};
</script>
You can use traditional JavaScript to solve your problem
// Reload the current page
window.location.reload();
Use window.location.reload(true); to force reload (ignore the browser cache)
Related
i have questions about data binding in vuejs and i hope everyone here can help me to solve this problem.
I'm in the stage of learning to use vuejs with laravel. I have problems doing data bindings in the data editing process, I can not display any information in the select box.
Next I include the data response that i want to display and the code.
data response
{
"data":{
"id":101,
"kode":"B100",
"nama":"Bendung Jules Rutherford",
"desa":{
"id":"5103050018",
"district_id":"5103050",
"name":"BONGKASA PERTIWI",
"district":{
"id":"5103050",
"city_id":"5103",
"name":"ABIANSEMAL",
"city":{
"id":"5103",
"province_id":"51",
"name":"KABUPATEN BADUNG",
"province":{
"id":"51",
"name":"BALI",
}
}
}
}
}
}
and this is the code :
<template>
<div>
<div v-if="!loading">
<div class="form-group row">
<label class="col-sm-3">Kode</label>
<div class="col-sm-9">
<input :class="{'is_invalid' : errors.kode}" v-model="bendung.kode" type="text" class="form-control" placeholder="B0001">
<div class="invalid-feedback" v-if="errors.kode">{{ errors.kode[0] }}</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3">Nama</label>
<div class="col-sm-9">
<input :class="{'is-invalid': errors.nama}" v-model="bendung.nama" type="text" class="form-control" placeholder="Bendungan Mengwi">
<div class="invalid-feedback" v-if="errors.nama">{{ errors.nama[0] }}</div>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.provinces }]">
<label class="col-sm-3">Provinsi</label>
<div class="col-sm-9">
<select #change="province" v-model="bendung.desa.district.city.province_id" class="form-control">
<option value="">Pilih Provinsi</option>
<option v-for="province in provinces" :value="province.id">
{{ province.name }}
</option>
</select>
</div>
</div>
<div :class="['form-group row', {'has-error' : errors.cities }]">
<label class="col-sm-3">Kota / Kabupaten</label>
<div class="col-sm-9">
<select #change="city" v-model="bendung.desa.district.city_id" class="form-control">
<option value="">Pilih Kota/Kabupaten</option>
<option v-for="city in cities" :value="city.id">
{{ city.name }}
</option>
</select>
</div>
</div>
</div>
<div class="row" v-else>
<div class="col-sm-12">
<content-placeholders>
<content-placeholders-text/>
</content-placeholders>
</div>
</div>
<div class="form-group row">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<a class="btn btn-success" href="#" :disabled="submiting" #click.prevent="update">
<font-awesome-icon :icon="['fas', 'spinner']" v-if="submiting" />
<font-awesome-icon :icon="['fas', 'check']" v-else/>
<span class="ml-1">Perbaharui</span>
</a>
<a href="/sda/bendung" class="btn btn-danger">
<font-awesome-icon :icon="['fas', 'times-circle']" /> Batal</a>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
errors: {},
bendung: {},
provinces: [],
cities:[],
districts: [],
state: {
province: '',
city: '',
district: '',
},
loading: true,
submiting: false
}
},
mounted() {
this.getBendung();
this.getProvinces();
},
methods: {
getBendung() {
this.loading = true;
let str = window.location.pathname;
let res = str.split("/");
axios.get(`${process.env.MIX_WEBSERVICE_URL}/sda/bendung/${res[3]}`)
.then(response => {
this.bendung = response.data.data;
this.state.province = this.bendung.desa.district.city.province_id;
})
.catch(error => {
this.$toasted.global.error('Bendung tidak ditemukan!');
location.href = '/sda/bendung';
})
.then(() => {
this.loading = false;
});
},
getProvinces() {
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/province`).then(response => {
this.provinces = response.data;
}).catch(error => console.error(error));
},
province() {
this.state.city = '';
const params = {
province: this.state.province
}
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/city`, {params}).then(response => {
this.cities = response.data;
}).catch(error => console.error(error));
},
city() {
this.state.district = '';
const params = {
city: this.state.city
};
// /location/district?city=cityId
axios.get(`${process.env.MIX_WEBSERVICE_URL}/location/district`, {params}).then(response => {
this.districts = response.data;
}).catch(error => console.error(error));
}
}
}
</script>
<style scoped>
</style>
the result is like this picture.
i want to show city name on select box but i got blank selectbox and when i change the selectbox (e.g provinsi/province), the other selectbox (e.g. kabupaten/kota/city) will change it data.
You could fetch new data when previous data has been changed.
Here is the working example: https://codesandbox.io/embed/vue-template-2zv2o
Have you tried to use the v-bind:key prop within your v-for loop?
v-bind:key="city.id"
or better with an additional index:
v-for="(city, index) in cities"
[...]
v-bind:key="`${index}-${city.id}`"
I'm building a CRUD web app using Laravel/Vue.js for the first time. I'm using a MySQL database and I used many Vue.js components, and each one can access a table in the database. Now I need to make some components to get data from other components to use it in a drop down, but I can't figure it out.
I tried using props but always get errors.
This is in the child vue:
<div class="form-group">
<select v-model="form.fabnom" type="text" name="fabnom" id="fabnom" class="form-control" :class="{ 'is-invalid': form.errors.has('fabnom') }">
<option v-for="fabriquant in fabriquants" :key="fabriquant.id" :value="fabriquant.fabnom">
</option>
</select>
<has-error :form="form" field="fabnom"></has-error>
</div>
<script>
export default {
data(){
return{
editmode: false,
machines :{},
form: new Form({
id:'',
code:'',
nom: '',
type:'',
serie:'',
date:'',
fabnom:'',
section:'',
unite:''
})
}
} ,
This is the API:
Route::apiResources([
'user' => 'API\UserController',
'fabriquant' => 'API\FabriquantController',
'machine' => 'API\MachineController',]);
Child controller(Parent one is nearly the same):
public function index()
{
//$this->authorize('isAdmin');
if (\Gate::allows('isAdmin')) {
return Machine::latest()->paginate(5);
}
}
public function store(Request $request)
{
$this->validate($request,[
'code' => 'required|string|max:191|unique:machines',
'nom' => 'required|string|max:191',
'type' => 'max:191',
'serie' => 'max:191',
'date' => 'max:191',
'fabnom' => 'max:191',
'section' => 'max:191',
'unite' => 'max:191',
]);
return Machine::create([
'code'=> $request['code'],
'nom'=> $request ['nom'],
'type'=> $request['type'],
'serie'=> $request['serie'],
'date'=> $request['date'],
'fabnom'=> $request['fabnom'],
'section'=> $request['section'],
'unite'=> $request['unite'],
]);
}
public function show($id)
{
//
}
public function update(Request $request, $id)
{
$machine = Machine::findOrFail($id);
$this->validate($request,[
'code' => 'required|string|max:191|unique:machines,code,'.$machine->id,
'nom' => 'max:191',
'type' => 'max:191',
'serie' => 'max:191',
'date' => 'max:191',
'fabnom' => 'max:191',
'section' => 'max:191',
'unite' => 'max:191',
]);
$machine->update($request->all());
return ['message' => 'Updated'];
}
public function destroy($id)
{
$machine = Machine::findOrFail($id);
// delete
$machine->delete();
return ['message' => 'Deleted'];
}
}
EDIT: You can see in the child component there is a string called fabnom and in the parent there is one also: so lets just say now I'm in the parent component and I added 3 items to its database via a modal each item has 6 columns in the database, one of them is called fabnom, now I passed to the child component page I opened an 'addNew' model and there is a dropdown box labeled fabnom which should have the 3 options that I already added I choose one of them and this value is going to be stored in the fabnom column of the database of the child component (I hope you get the idea guys)
This the parent.vue(The child one looks pretty the same the only difference that it has also a dropdown box in its 'addNew' model as mentioned up which is causing the problem):
<template>
<div class="container">
<div class="row mt-5" v-if="$gate.isAdmin()">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Liste des Fabriquants</h3>
<div class="card-tools">
<button class="btn btn-success" #click="newModal">
Ajouter</button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<tbody>
<tr>
<th>Nom</th>
<th>Adresse</th>
<th>Téléphone</th>
<th>Fax</th>
<th>E-mail</th>
</tr>
<tr v-for="fabriquant in fabriquants.data" :key="fabriquant.id">
<td>{{fabriquant.fabnom}}</td>
<td>{{fabriquant.adresse}}</td>
<td>{{fabriquant.tel}}</td>
<td>{{fabriquant.fax}}</td>
<td>{{fabriquant.email}}</td>
<td>
<a href="#" #click="editModal(fabriquant)">
<i class="fa fa-edit"></i>
</a>
/
<a href="#" #click="deleteFabriquant(fabriquant.id)">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
</tbody></table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="fabriquants" #pagination-change-page="getResults"></pagination>
</div>
</div>
<!-- /.card -->
</div>
</div>
<div v-if="!$gate.isAdmin()">
<not-found></not-found>
</div>
<!-- Modal -->
<div class="modal fade" id="Ajouter" tabindex="-1" role="dialog" aria-labelledby="AjouterLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editmode" id="AjouterLabel">Ajouter</h5>
<h5 class="modal-title" v-show="editmode" id="AjouterLabel">Modifier</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form #submit.prevent="editmode ? updateFabriquant() : createFabriquant()">
<div class="modal-body">
<div class="form-group">
<input v-model="form.fabnom" type="text" name="fabnom"
placeholder="Nom"
class="form-control" :class="{ 'is-invalid': form.errors.has('fabnom') }">
<has-error :form="form" field="fabnom"></has-error>
</div>
<div class="form-group">
<input v-model="form.adresse" type="text" name="adresse"
placeholder="Adresse"
class="form-control" :class="{ 'is-invalid': form.errors.has('adresse') }">
<has-error :form="form" field="adresse"></has-error>
</div>
<div class="form-group">
<input v-model="form.tel" type="text" name="tel"
placeholder="Téléphone"
class="form-control" :class="{ 'is-invalid': form.errors.has('tel') }">
<has-error :form="form" field="tel"></has-error>
</div>
<div class="form-group">
<input v-model="form.fax" type="text" name="fax"
placeholder="Fax"
class="form-control" :class="{ 'is-invalid': form.errors.has('fax') }">
<has-error :form="form" field="fax"></has-error>
</div>
<div class="form-group">
<input v-model="form.email" type="email" name="email"
placeholder="E-mail"
class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
<has-error :form="form" field="email"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Fermer</button>
<button v-show="editmode" type="submit" class="btn btn-success">Modifier</button>
<button v-show="!editmode" type="submit" class="btn btn-primary">Ajouter</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
editmode: false,
fabriquants :{},
form: new Form({
id:'',
fabnom:'',
adresse: '',
tel:'',
fax:'',
email:''
})
}
},
methods: {
getResults(page = 1) {
axios.get('api/fabriquant?page=' + page)
.then(response => {
this.fabriquants = response.data;
});
},
updateFabriquant(){
this.$Progress.start();
// console.log('Editing data');
this.form.put('api/fabriquant/'+this.form.id)
.then(() => {
// success
$('#Ajouter').modal('hide');
Swal.fire(
'Modifié!',
'Informations modifiés!',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreate');
})
.catch(() => {
this.$Progress.fail();
});
},
editModal(fabriquant){
this.editmode = true;
this.form.reset();
$('#Ajouter').modal('show');
this.form.fill(fabriquant);
},
newModal(){
this.editmode = false;
this.form.reset();
$('#Ajouter').modal('show');
},
deleteFabriquant(id){
Swal.fire({
title: 'Voulez vous vraiment supprimer cet fabriquant?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Oui, Supprimer!',
}).then((result) => {
// Send request to the server
if (result.value) {
this.form.delete('api/fabriquant/'+id).then(()=>{
Swal.fire(
'Supprimé!',
'Element supprimé.',
'success'
)
Fire.$emit('AfterCreate');
}).catch(()=> {
Swal.fire("Echec!", "Il y'a un problème.", "warning");
});
}
})
},
loadFabriquants(){
if(this.$gate.isAdmin()){
axios.get("api/fabriquant").then(({ data }) => (this.fabriquants = data));
}
},
createFabriquant(){
this.$Progress.start();
this.form.post('/api/fabriquant')
.then(()=>{
Fire.$emit('AfterCreate');
$('#Ajouter').modal('hide');
toast.fire({
type: 'success',
title: 'Fabriquant ajouté',
})
this.$Progress.finish();
})
.catch(()=>{
})
}
},
created() {
this.loadFabriquants();
Fire.$on('AfterCreate',()=>{
this.loadFabriquants();
});
}
}
</script>
If I understand your main issue, you could use something like an instance property or a javascript file to hold variables in client-side storage.
From what I understand, what you need is a way to first get data from your MySQL using one component, and then second, use that data in all the rest of your components. If so, I had this need with my current project about 2 months ago.
The only problem is that I'm not using Laravel/Vue but Vue.js, VueApollo, and GraphQL. Although, I'm pretty sure --and hope-- the way that I fixed my issue will only differ in syntax from the way you could solve yours.
I used a component to query some info from the user right after they log in.
Vue/Apollo Query
apollo: {
// Simple query that gets user info
me: {
query: gql` //GraphQL
{
me {
id
fullName
}
}
`,
loadingKey: "isLoading" //tracks results that are still loading.
}
}
Then I wanted to store the user's 'fullName' somewhere so that my navigation component could always use it. So I created a file:
src/config/credentialStore.js
In this file I created a displayName variable like this:
export const credentialStore = {
displayName: "",
userID: ""
};
Back in the component where I have the 'me' query, I destructured the data that was returned from the query with a function.
apollo: {
// Simple query that gets user info
me: {
query: gql`
{
me {
id
fullName
}
}
`,
loadingKey: "isLoading",
result({ data }) { //data is basically an object with the results of the query
this.$credentials.userId = data.me.id;
this.$credentials.displayName = data.me.fullName;
} //using this.$credentials.displayName will let me use that string from any component.
}
}
So you would do something like that and then maybe something like this:
<script>
export default {
data(){
return{
editmode: false,
fabriquants :{},
form: new Form({
id: this.$credentialStore.id,
fabnom:this.$credentialStore.fabnom, //what's a fabnom? 🤔
• • •
})
}
},
I hope this helps you or someone else.
So for the past few days i have tried to make this template auto reload when something new has happened. That is when "Notifications" has been modified, either by new entry has ben added or that a notification has been marked as read.
I use a dropdown to show the results, and right now i have to reload the whole page when something happens. Which isn't very nice for a modern application.
PS. I'm completely new to Vue, since this integration with laravel notifications.
This is my .vue file (and you can see i have tried a few things myself without success)
<template>
<li class="dropdown">
<a href="#" class="dropdown-toggle icons" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false">
<span class="badge badge-dark badge-corner fs-11">{{ notifications.length }}</span>
<i class="fas fa-bell fs-15" style="color: #444;"></i>
</a>
<ul
class="dropdown-menu dropdown-menu-right notify-drop">
<li>
<div class="notify-drop-title">
<div class="row">
<div class="col-10">Notifikationer (<b>{{ notifications.length }}</b>)</div>
<div class="col-2 text-right">
<button class="rIcon allRead"
data-tooltip="tooltip"
data-placement="bottom"
title="Markera alla som lästa"><i
class="fa fa-bullseye fs-12"></i>
</button>
</div>
</div>
</div>
<!-- end notify title -->
<!-- notify content -->
<div class="drop-content">
<div class="thisItem" v-for="notification in notifications" :key="notification.id">
<div class="row pl-10">
<div class="col-1">
<div
v-if="notification.data.type === 'friend' || notification.data.type === 'friendAccept'">
<i class="fas fa-heart fs-25 primary mt-5"></i>
</div>
<div v-if="notification.data.type === 'friendDeny'">
<i class="fas fa-heart-broken fs-25 primary mt-5"></i>
</div>
</div>
<div class="col-10 ml-5">
<button class="float-right rIcon mr-1" data-toggle="tooltip"
data-placement="top" title="Markera som läst"
v-on:click="MarkAsRead(notification)">
<i class="fa fa-bullseye fs-12"></i>
</button>
<a class="fs-14 m-0" style="text-transform: none;" :href="'/profile/' + notification.data.accessurl">{{
notification.data.fromuser }}</a>
<span class="fs-12 m-0 text-muted">{{ notification.data.message }}</span>
<div v-if="notification.data.type === 'friend'">
<button type="button" class="btn btn-primary btn-sm"
v-on:click="AcceptFriend(notification)">Acceptera
</button>
<button type="button" class="btn btn-primary btn-sm"
v-on:click="DenyFriend(notification)">Neka
</button>
</div>
</div>
</div>
</div>
</div>
<div class="notify-drop-footer text-center">
<i class="fa fa-eye"></i> Visa Alla
</div>
</li>
</ul>
</li>
</template>
<script>
export default {
props: ['notifications'],
methods: {
MarkAsRead: function (notification) {
const data = {
id: notification.id
};
const self = notification;
axios.post('/notification/read', data).then(response => {
//self.id = '';
//self.$forceUpdate();
//self.notification += 1;
//self.setState({notification: response.data});
//self.data.fromuser = '';
//self.data.message = response.data;
//this.notifications.splice(notification,1);
console.log(response.data);
});
},
AcceptFriend: function (notification) {
const data = {
id: notification.id,
friendid: notification.data.itemid,
fromuserid: notification.data.fromuserid
};
axios.post('/notification/acceptFriend', data).then(response => {
console.log(response.data);
});
axios.post('/notification/read', data).then(response => {
console.log(response.data);
});
},
DenyFriend: function (notification) {
const data = {
id: notification.id,
friendid: notification.data.itemid,
fromuserid: notification.data.fromuserid
};
axios.post('/notification/denyFriend', data).then(response => {
console.log(response.data);
});
axios.post('/notification/read', data).then(response => {
console.log(response.data);
});
}
}
}
</script>
My app.js
Vue.component('notification', require('./components/Notification.vue'));
const app = new Vue({
el: '#app',
data: {
notifications: ''
},
created() {
axios.post('/notification/get').then(response => {
this.notifications = response.data;
});
var userId = $('meta[name="userId"]').attr('content');
Echo.private('App.User.' + userId).notification((notification) => {
this.notifications.push(notification);
});
},
computed: {
notifications: function () {
return this
}
}
});
Thank you in advance for anyone who can help me solve this!
As I understand it, do you want to render multiple notifications each time you receive new notifications data?
In such a case, you can use props.
if you inject props to notification component, the notification component will be re-rendered whenever the props changes
example
<notification :notifications='notifications'><notification>
https://v2.vuejs.org/v2/guide/components-props.html
I use Laravel and Vue. I have two components: parent and child.
Parent:
<template>
<div>
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Application id</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Picture</th>
<th scope="col">URL</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="sportSite in sportSites">
<th scope="row">{{ sportSite.id }}</th>
<td>
<template v-for="application in sportSite.applications">
id {{ application.id }} => {{ application.name }} <br>
</template>
</td>
<td>{{ sportSite.name }}</td>
<td>{{ sportSite.description }}</td>
<td>
<img style="width: 100px; height: 100px;" :src="sportSite.image" >
</td>
<td>
<a :href="sportSite.url" target="_blank">{{ sportSite.url }}</a>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { EventBus } from '../../app';
export default {
name: "SportSitesTable",
mounted(){
this.loadTable();
this.getApplications();
},
methods:{
loadTable: function () {
window.axios.get('/sport_sites_all')
.then(resp => {
this.sportSites = resp.data.data;
}).catch(err => {
console.error(err);
});
},
getApplications: function () {
window.axios.get('/applications/all')
.then(resp => {
this.applicationsAll = resp.data.applications.data;
}).catch(err => {
console.error(err);
});
}
},
data(){
return {
sportSites: [],
applicationsAll: [],
}
},
}
</script>
Child:
<template>
<div>
<button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#sportSiteAdd">
Add
</button>
<div class="modal fade" id="sportSiteAdd" tabindex="-1" role="dialog" aria-labelledby="sportSiteAddLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="sportSiteAddLabel">Add sport site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul class="alert-danger">
<li v-for="error in errors">
{{ error[0] }}
</li>
</ul>
<form>
<div class="form-group">
<label for="name">Title</label>
<input type="text" class="form-control" id="name" name="name" v-model="formFields.name">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input type="text" class="form-control" id="image" name="image" v-model="formFields.image">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url" v-model="formFields.url">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" v-model="formFields.description"></textarea>
</div>
<div>
<label class="typo__label">Applications </label>
<multiselect v-model="formFields.applications"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applications"
:multiple="true"
:taggable="true">
</multiselect>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" v-on:click="submit">Save</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { EventBus } from '../../app';
import Multiselect from 'vue-multiselect'
export default {
name: "SportSitesAdd",
props: ['applicationsAllList'],
methods:{
submit: function (e) {
window.axios.post('/sport_site/add/', this.formFields)
.then(res => {
console.log('Saved!');
$('#sportSiteAdd').modal('hide');
this.formFields.name = '';
this.formFields.image = '';
this.formFields.url = '';
this.formFields.description = '';
EventBus.$emit('reloadApplicationsTable');
}).catch(err => {
if(err.response.status === 422){
this.errors = err.response.data.errors || [];
}
console.error('Error of saving!');
});
},
},
data(){
return {
formFields: {
name: '',
image: '',
url: '',
description: '',
applications: this.applicationsAllList,
},
errors: [],
}
},
components: {
Multiselect
},
}
</script>
The parent component is a table. Child component is a form for the table. I pass a data from the parent to the child via props:
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
In the child component I have a plugin for creating a multiple select. The plugin requires 'options' and 'values' collections. It's very simple, documentation with my case is here https://vue-multiselect.js.org/#sub-tagging. At the result I want to see the following: all items on the select are selected. But I have just the empty collection during mounting of the child component. I have available items on the 'select' but I dont know how I can make it selected by default. Obviously, I need to copy the applicationsAllList into local data() of child component and use it. But it not available during mounted and beforeMounted.
console.log tells me that the child is faster.
you're missing #tag function & v-model, in this case, must be array, You need to use applicationsAllList props directly on options
<multiselect v-model="formFields.value"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applicationsAllList"
:multiple="true"
#tag="addTag"
:taggable="true">
</multiselect>
in methods add addTag function and add value as array
data() {
return {
formFields: {
name: '',
value: [],
image: '',
url: '',
description: '',
},
errors: [],
}
},
methods: {
addTag (newTag) {
const tag = {
name: newTag,
code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.options.push(tag)
this.value.push(tag)
}
}
Hello I want to make a loop to iterate an array of data retrieve from a controller but I have an error message in vue js I can not find where is my error help me please I start with a vue js
here is my code
controller.php
public function index(){
$post= Posts::with('likes','comments', 'user')->orderBy('created_at','DESC')->get();
return $post ;
}
vue.js
const root = new Vue({
el: '#root',
data: {
msg: 'Update New Post:',
content: '',
posts: []
},
ready: function ready() {
this.created();
},
created: function created() {
var _this = this;
axios.get('http://localhost:8000/mur/posts')
.then(response => {
_this.posts = response.data;
//we are putting data into our posts array
console.log(response.data);
// show if success
Vue.filter('myOwnTime', function(value){
return moment(value).fromNow();
});
})
.catch(function (error) {
console.log(error); // run if we have error
});
}
},
view
<div v-for="post, key in posts">
<div class="col-md-12 col-sm-12 col-xs-12 all_posts">
<div class="col-md-1 pull-left">
<img :src="'{{asset('storage/avatar')}}/' + post.avatar"
style="width:50px;">
</div>
<div class="col-md-10" style="margin-left:10px">
<div class="row">
<div class="col-md-11">
<p><a :href="'{{url('profile')}}/' + post.slug" class="user_name"> #{{post.user.name}}</a> <br>
<span style="color:#AAADB3"> #{{ post.created_at }}
<i class="fa fa-globe"></i></span></p>
</div>
<div class="col-md-1 pull-right">
#if(Auth::check())
<!-- delete button goes here -->
<a href="#" data-toggle="dropdown" aria-haspopup="true">
{{--<img src="{{Config::get('app.url')}}/public/img/settings.png" width="20">--}}
</a>
<div class="dropdown-menu">
<li><a>some action here</a></li>
<li><a>some more action</a></li>
<div class="dropdown-divider"></div>
<li v-if="post.user_id == '{{Auth::user()->id}}'">
<a #click="deletePost(post.id)">
<i class="fa fa-trash"></i> Delete </a>
</li>
</div>
#endif
</div>
</div>
</div>
<p class="col-md-12" style="color:#000; margin-top:15px; font-family:inherit" >
#{{post.content}}
</p>
<div style="padding:10px; border-top:1px solid #ddd" class="col-md-12">
<!-- like button goes here -->
#if(Auth::check())
<div v-for="">
<div v-if="">
<p class="likeBtn" #click="likePost(post.id)">
<i class="fa fa-heart-o"></i>
</p>
</div>
</div>
data : #{{ post.likes.length }}
#endif
</div>
</div>
</div>
web.php
Route::get('mur/posts', 'PostController#index');
posts [ ] return this
[{"id":8,
"user_id":3,
"content":"content 1",
"status":0,
"created_at":"2017-12-27 22:43:20",
"updated_at":"2017-12-27 22:43:20",
"likes":[{"id":2,"posts_id":7,"user_id":3,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{
"id":3,"name":"toto","sulg":"toto","email":"toto#hotmail.fr","avatar":"215563.jpg","is_actif":"activ\u00e9","created_at":"2017-12-06 15:30:42","updated_at":"2017-12-06 17:04:41"}
},
{"id":7,
"user_id":9,
"content":"coucou",
"status":0,
"created_at":"2017-12-27 16:07:01",
"updated_at":"2017-12-27 16:07:01",
"likes":[{"id":2,"posts_id":7,"user_id":4,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{"id":9,"name":"blop","sulg":"blop","email":"blop#gmail.com","avatar":"logoBee.png","is_actif":"activ\u00e9","created_at":"2017-12-17 14:37:29","updated_at":"2017-12-17 14:37:29"}}
error in console