Vue v-for list does not update after data changed - vuejs2

The idea is simple:
The Vue instance loads groups from an API.
This groups are shown using a v-for syntax.
The groupdata is formatted properly, and added to app.groups using .push function, which should update the v-for list.
However, the v-for list will not update.
When I change v-for="group in groups" (loaded externally) to v-for="group in people" (already in the app), it does give output.
HTML
<div id="app" class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Realtime Socket Chat</div>
<div class="panel-body" v-if="dataReady" v-for="group in groups"> #{{ group.name }}
<a v-bind:href="group.link" class="pull-right">
<div class="btn btn-xs btn-primary">
Join
</div>
</a>
</div>
</div>
</div>
</div>
Vue
var app = new Vue({
el: "#app",
data: {
groups: [],
people: [{name: 'hi'}, {name: 'lol'}]
},
mounted: function() {
this.load()
},
methods: {
load: function() {
axios.get('http://example.com/groups')
.then(function (response) {
console.log(response.data.groups);
response.data.groups.forEach(function(group) {
app.groups.push(group);
});
// app.groups.forEach(function (group) {
// group.link = '/g/' + group.id + '/join';
// });
// console.log(response.data.groups);
console.log(this.groups); //outputs [{...}, {...}] so this.groups is good
})
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
});
API
{
"groups": [
{
"id": 1,
"name": "Photography Chat",
"created_at": "2017-11-26 08:50:16",
"updated_at": "2017-11-26 08:50:16"
},
{
"id": 2,
"name": "Media Chat",
"created_at": "2017-11-26 08:50:16",
"updated_at": "2017-11-26 08:50:16"
}
]
}

It seems like app is undefined when your load function is executed. So, using ES6 arrow function syntax, your load function should look like this:
load: function() {
axios.get('http://example.com/groups')
.then(response => {
let groups = response.data.groups || []
groups.forEach(group => {
this.groups.push(group)
})
console.log(this.groups)
})
.catch(error => {
this.errors.push(error)
console.log(error)
})
}

A fact I left out in the question (because I assumed it would not matter) was that I am working within the Laravel framework, Laravel automatically imports Vuejs within main.js. Which does not play nice when Vue is loaded in additionally. I removed main.js and it works.

Related

Cant store api data called by axios in array through mounted, unless clicking on <Root> element from vue devtools (in browser)

i'm using axios to get data from api and store in an array after mounting then run a search query in the array later on, but it's not working unless i click on Root element in browsers Vue developer tools, after i click on vue Root element from vue dev tool everything works fine.Here is my code..
<script type="module">
const vueApp = new Vue({
el: "#pos",
data: {
searchTerm: "",
allProducts: [],
selectedProducts: [],
suggestions: []
},
mounted: function (){
axios.get("api/products").then( res => this.allProducts = res.data );
},
methods: {
select(item){
this.selectedProducts.push(item);
this.suggestions = [];
}
},
computed:{
matches(){
if(!this.searchTerm) return;
this.suggestions = this.allProducts.filter(sP=>(sP.prod_name).includes(this.searchTerm));
}
}
});
</script>
//HTML below------------------
<div id="pos">
<input type="text" v-model="searchTerm">
<ul v-for="match in suggestions">
<li #click="select(match)">
{{match.prod_name}}
</li>
</ul>
<table>
<tr v-for="(product,i) in selectedProducts">
<td>#{{product.prod_name}}</td>
</tr>
</table>
</div>
const vueApp = new Vue({
el: "#pos",
data: {
searchTerm: "",
allProducts: [],
selectedProducts: [],
suggestions: []
},
mounted: function() {
axios.get("api/products").then(res => this.allProducts = res.data);
},
methods: {
select(item) {
this.selectedProducts.push(item);
this.suggestions = [];
}
},
computed: {
matches() {
if (!this.searchTerm) return;
this.suggestions = this.allProducts.filter(sP => (sP.prod_name).includes(this.searchTerm));
}
}
});
<div id="pos">
<input type="text" v-model="searchTerm">
<ul v-for="match in suggestions">
<li #click="select(match)">
{{match.prod_name}}
</li>
</ul>
</div>
As I mentioned in the comments on your question, this is an error I cannot seem to understand how you are getting. I sense there is information that we are not being presented with.
As such, here is a quick "working" example of fetching items from the mounted lifecycle hook in a component. Note: If you are creating the component via a Single-File Component (.vue files) then don't worry too much about the declaration, pay attention only to the data and mounted methods.
const App = Vue.component('App', {
template: `<div>
<input v-model="searchTerm" type="search">
{{items.length}} results fetched
</div>`,
data() {
return {
searchTerm: '',
items: []
}
},
mounted() {
//Timeout used to mimic axios query
setTimeout(()=> this.items= [1,2,3,4], 1000)
}
});
const app = new App({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">Placeholder</div>
Edit
The code you have given us after your update seems to be working just fine. See the below snippet.
I noticed you are looping over suggestions but that value is never updated anywhere in your given code.
const vueApp = new Vue({
el: "#pos",
data: {
searchTerm: "",
allProducts: [],
selectedProducts: [],
suggestions: []
},
mounted: function() {
setTimeout(() => this.allProducts = [1,2,3,4,5], 1000);
},
methods: {
select(item) {
this.selectedProducts.push(item);
this.suggestions = [];
}
},
computed: {
matches() {
if (!this.searchTerm) return;
this.suggestions = this.allProducts.filter(sP => (sP.prod_name).includes(this.searchTerm));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="pos">
<input type="text" v-model="searchTerm">
<ul v-for="match in suggestions">
<li #click="select(match)">
{{match.prod_name}}
</li>
</ul>
{{allProducts.length}} results loaded
</div>
mounted: function(){
var _self = this;
axios.get("api/products").then( res => _self.allProducts = res.data );
}

Getuikit 3 sortable element on moved not triggered

For some reason I can't perform actions after the sortable elements are moved. The event UIkit.util.on('#sortable', 'moved', function (item) {}); is not being called/triggered.
The app is made with vue.js, but I get no error and every other uikit functionality works just fine. There are ~600 line of code so, I'll just show the ones that matter (I think).
<template>
<div class="products">
<MainMenu />
<div id="ordering" uk-offcanvas="overlay: true">
<div class="uk-offcanvas-bar" style="width:500px">
<button class="uk-offcanvas-close" type="button" uk-close></button>
<div>Drag to re-arrange the fields order<br><br>
<ul id="sortable" class="uk-grid-small uk-child-width-1-1 uk-text-center" uk-sortable="handle: .uk-card" uk-grid>
<li v-for="(data, idx) in computedData" :key="idx" :id="data.product_field_name">
<div class="uk-card uk-card-default uk-card-body uk-padding-small">{{data.product_field_name}}</div>
</li>
</ul>
</div>
</div>
</div>
<button type="button" class="uk-button uk-button-default" uk-toggle="target: #ordering"><span uk-icon="move"></span> Field Ordering</button>
<!-- REST OF HTML GOES HERE: FORMS, MODALS, ETC. -->
</div>
</template>
<script>
UIkit.notification('test message','danger'); //THIS TRIGGERS OK
//UIKit ordering action - THIS DOES NOT
UIkit.util.on('#sortable', 'moved', function (item) {
console.log('moved triggered');
});
// # is an alias to /src
import MainMenu from "#/components/MainMenuEMVO.vue";
import axios from "axios";
export default {
name: "products",
components: {
MainMenu
},
data() {
return {
add_dependency: {
field: "",
field_selection: ""
},
remove_dependency: {
id: "",
field_name: "",
dependency_field: "",
dependency_rule: "",
dependency_value: "",
enforcing_value: "",
},
productFields: "",
lookupTables: "",
dependencies: "",
departments: "",
search: "",
computedFields: "",
};
},
mounted() {
let stateCheck = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(stateCheck);
this.getProductsConfig();
}
}, 100);
},
computed: {...},
methods: {
getProductsConfig(){...},
enableEdit(id){...},
cancelEdit(id){...},
submitEdit(id){...},
addRule(id, field_name){...},
removeDependency(fieldName, id){...}
}
};
</script>
As mentioned before there are no errors or even warnings in console, so I really don't event know where to start looking at this.
I managed to resolve the problem, so if anyone has the same issue:
Once I moved the code into the mounted() method of the vue.js it all works fine.
mounted() {
//UIKit ordering action - THIS DOES NOT
UIkit.util.on('#sortable', 'moved', function (item) {
console.log('moved triggered');
});
let stateCheck = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(stateCheck);
this.getProductsConfig();
}
}, 100);
},
the UIkit.notification works fine, but I guess since the util is attached to event it has to be made available to vue on startup.
If you added UIkit as <script src="./src/js/uikit.min.js"></script> in your index.html then you can't use it inside Vue as expected, instead do:
npm i --save uikit
then in your Component
import UIkit from "uikit";
after that you can use everywhere
methods: {
alertOnClick(msg) {
UIkit.notification(msg, "danger");
}
}
}

vue.js – get new data information

I'm building a chrome extension using vue.js. In one of my vue components I get tab informations of the current tab and wanna display this information in my template. This is my code:
<template>
<div>
<p>{{ tab.url }}</p>
</div>
</template>
<script>
export default {
data() {
return {
tab: {},
};
},
created: function() {
chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, function(tabs) {
this.tab = tabs[0];
});
},
};
</script>
The Problem is, that the template gets the data before it's filled through the function. What is the best solution for this problem, when the tab data doesn't change after it is set once.
Do I have to use the watched property, although the data is only changed once?
// EDITED:
I've implemented the solution, but it still doesn't work. Here is my code:
<template>
<div>
<div v-if="tabInfo">
<p>set time limit for:</p>
<p>{{ tabInfo.url }}</p>
</div>
<div v-else> loading... </div>
</div>
</template>
<script>
export default {
data() {
return {
tabInfo: null,
};
},
mounted() {
this.getData();
},
methods: {
getData() {
chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, function(tabs) {
console.log(tabs[0]);
this.tabInfo = tabs[0];
});
},
},
};
</script>
The console.log statement in my getData function writes the correct object in the console. But the template only shows the else case (loading...).
// EDIT EDIT
Found the error: I used 'this' in the callback function to reference my data but the context of this inside the callback function is an other one.
So the solution is to use
let self = this;
before the callback function and reference the data with
self.tab
You could initialize tab to null (instead of {}) and use v-if="tabs" in your template, similar to this:
// template
<template>
<div v-if="tab">
{{ tab.label }}
<p>{{ tab.body }}</p>
</div>
</template>
// script
data() {
return {
tab: null,
}
}
new Vue({
el: '#app',
data() {
return {
tab: null,
}
},
mounted() {
this.getData();
},
methods: {
getData() {
fetch('https://reqres.in/api/users/2?delay=1')
.then(resp => resp.json())
.then(user => this.tab = user.data)
.catch(err => console.error(err));
}
}
})
<script src="https://unpkg.com/vue#2.5.17"></script>
<div id="app">
<div v-if="tab">
<img :src="tab.avatar" width="200">
<p>{{tab.first_name}} {{tab.last_name}}</p>
</div>
<div v-else>Loading...</div>
</div>

Nested Components and Proper Wrapping Techniques in VueJS

I'm trying to put Bootstrap Select2 in a Vue wrapper. Somehow, my code works. But It doesn't seem proper to me.
I found a reference in here https://v2.vuejs.org/v2/examples/select2.html
In the VueJS website example, the el is empty. I didn't stick to this concept where in the new Vue part, they included a template because my el have sidebars and other stuffs also. What I did was I added a
<admin-access></admin-access>
to a section in the HTML.
I think I made my component nested which I'm skeptical if it is proper in VueJS.
Is there a better way to code this?
Templates
<template id="select2-template">
<select>
<slot></slot>
</select>
</template>
<template id="admin-access">
<div>
<transition name="access" enter-active-class="animated slideInRight" leave-active-class="animated slideOutRight" appear>
<div class="box box-solid box-primary" v-if="admin" key="create">
<div class="box-header with-border">
<i class="fa fa-text-width"></i>
<h3 class="box-title">Create Admin</h3>
</div>
<div class="box-body">
<form action="" class="search-form">
<div class="form-group">
<label for="search_user_admin">Search User</label>
<select2 name="search_user_admin" id="search-user-admin" class="form-control select2" :options="options" v-model="selected">
<option disabled value="0">Select one</option>
</select2>
</div>
</form>
</div>
</div>
</transition>
</div>
</template>
Script
Vue.component('admin-access', {
template: '#admin-access',
props: ['options', 'value'],
created: function() {
$('#search-user-admin').select2({
placeholder: "Select User",
allowClear: true
});
},
data: function() {
return {
admin : true,
selected : false
}
},
});
Vue.component('select2', {
template: '#select2-template',
data: function() {
return {
selected: 0,
options: [
{ id: 1, text: 'Hello' },
{ id: 2, text: 'Darkness' },
{ id: 3, text: 'My' },
{ id: 4, text: 'Old' },
{ id: 5, text: 'Friend' }
]
}
},
mounted: function() {
var vm = this;
$(this.$el).select2({
data: this.options,
placeholder: "Select an option",
})
.val(this.value)
.trigger('change')
.on('change', function () {
vm.$emit('input', this.value);
});
},
watch: {
value: function (value) {
$(this.$el).val(value).trigger('change');
},
options: function (options) {
$(this.$el).select2({ data: options });
}
},
destroyed: function () {
$(this.$el).off().select2('destroy');
}
});
var admin = new Vue({
el: '#app'
});
There's nothing wrong with nesting components in the first place. But you have to keep in mind that nesting them, or just in general, just wrapping generic html components like a select into a Vue Component is very costly when it comes to rendering, especially when you are nesting them. Typically when all your component does is just wrapping a simple HTMl element with some styles, you should probably just use generic HTML with classes here, for performance sake.
Also, I'd try to get rid of all the jQuery code inside of Vue Components. Vue offers all the functionality that jQuery has and it'll just increase loading times further.

Updating custom component's form after getting a response

I'm trying to load in a Tutor's profile in a custom component with Laravel Spark. It updates with whatever I enter no problem, but the is always empty when loaded.
The component itself is as follows:
Vue.component('tutor-settings', {
data() {
return {
tutor: [],
updateTutorProfileForm: new SparkForm({
profile: ''
})
};
},
created() {
this.getTutor();
Bus.$on('updateTutor', function () {
this.updateTutorProfileForm.profile = this.tutor.profile;
});
},
mounted() {
this.updateTutorProfileForm.profile = this.tutor.profile;
},
methods: {
getTutor() {
this.$http.get('/tutor/current')
.then(response => {
Bus.$emit('updateTutor');
this.tutor = response.data;
});
},
updateTutorProfile() {
Spark.put('/tutor/update/profile', this.updateTutorProfileForm)
.then(() => {
// show sweet alert
swal({
type: 'success',
title: 'Success!',
text: 'Your tutor profile has been updated!',
timer: 2500,
showConfirmButton: false
});
});
},
}
});
Here's the inline-template I have:
<tutor-settings inline-template>
<div class="panel panel-default">
<div class="panel-heading">Tutor Profile</div>
<form class="form-horizontal" role="form">
<div class="panel-body">
<div class="form-group" :class="{'has-error': updateTutorProfileForm.errors.has('profile')}">
<div class="col-md-12">
<textarea class="form-control" rows="7" v-model="updateTutorProfileForm.profile" style="font-family: monospace;"></textarea>
<span class="help-block" v-show="updateTutorProfileForm.errors.has('profile')">
#{{ updateTutorProfileForm.errors.get('profile') }}
</span>
</div>
</div>
</div>
<div class="panel-footer">
<!-- Update Button -->
<button type="submit" class="btn btn-primary"
#click.prevent="updateTutorProfile"
:disabled="updateTutorProfileForm.busy">
Update
</button>
</div>
</form>
</div>
Very new to Vue and trying to learn on the go! Any help is much appreciated!
OK, firstly a bus should be used for communication between components, not within the components themselves, so updateTutor should be a method:
methods: {
getTutor() {
this.$http.get('/tutor/current')
.then(response => {
this.tutor = response.data;
this.updateTutor();
});
},
updateTutor() {
this.updateTutorProfileForm.profile = this.tutor.profile;
}
}
Now for a few other things to look out for:
Make sure you call your code in the order you want it to execute, because you appear to be emitting to the bus and then setting this.tutor but your function uses the value of this.tutor for the update of this.updateTutorProfileForm.profile so this.tutor = response.data; should come before trying to use the result.
You have a scope issue in your $on, so the this does not refer to Vue instance data but the function itself:
Bus.$on('updateTutor', function () {
// Here 'this' refers to the function itself not the Vue instance;
this.updateTutorProfileForm.profile = this.tutor.profile;
});
Use an arrow function instead:
Bus.$on('updateTutor', () => {
// Here 'this' refers to Vue instance;
this.updateTutorProfileForm.profile = this.tutor.profile;
});
Make sure you are not developing with the minified version of Vue from the CDN otherwise you will not get warnings in the console.
I can't see how you are defining your bus, but it should just be an empty Vue instance in the global scope:
var Bus = new Vue();
And finally, your mounted() hook is repeating the created() hook code, so it isn't needed. My guess is that you were just trying a few things out to get the update to fire, but you can usually do any initialising of data in the created() hook and you use the mounted hook when you need access to the this.$el. See https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks