I have a very simple application that initiates a search and filter based on the query parameters. When I initiate the query https://example.com/?filter=2134 it initiates the search and shows me the result of schools. This means that the searchSchools() function is being executed and the results are being fetched.
However, then I execute the filterSuggestions() function, it doesn't seem to apply the filter.
However, when I do a console.log(suggestedSchools) within mounted, it returns empty.
const app = new Vue({
el: '#app',
data: {
suggestedSchools : [],
filter : '',
filteredSchools : [],
},
mounted: function () {
// checking some get parameters and conditions and triggering the search
this.searchSchools(); // function that initiates ajax request and store the results into suggestedSchools
this.filter = 2134; // the postcode value comes from the get request
this.filterSuggestions(); // function that applies the postcode filter to the suggestedSchools list and assign the filtered results to filteredSchools.
},
methods: {
searchSchools() {
axios.get('/search-school').then(response => {
this.suggestedSchools = response.data;
this.filteredSchools = response.data;
})
},
filterSuggestions()
{
this.filteredSchools = this.suggestedSchools.filter(school => {
// filtering logic
}
},
},
});
That's because the searchSchools function makes an asynchronous request so when filterSuggestions function is executed it finds the suggestedSchools array empty. I suggest it should be more like this:
const app = new Vue({
el: '#app',
data: {
suggestedSchools : [],
filter : '',
filteredSchools : [],
},
mounted: function () {
// checking some get parameters and conditions and triggering the search
this.searchSchools(); // function that initiates ajax request and store the results into suggestedSchools
this.filter = 2134; // the postcode value comes from the get request
},
methods: {
searchSchools() {
axios.get('/search-school').then(response => {
this.suggestedSchools = response.data;
this.filteredSchools = response.data;
this.filteredSuggestions()
})
},
filterSuggestions()
{
this.filteredSchools = this.suggestedSchools.filter(school => {
// filtering logic
}
},
},
});
Related
var vue_app = new Vue({
el: '#id1',
data: {
v1:[],
},
methods:{
pushUnique: function() {
this.v1.push({'id':1,'name':'josh'});
this.v1.push({'id':1,'name':'josh'}); //this should not work.
},
},
});
In above code the second push should not execute. I would like to keep id unique. How can this be done in Vue.
THanks
I would move to storing data in an object (keyed by id) and use a computed property to produce your v1 array. For example
data: {
v1obj: {}
},
computed: {
v1 () {
return Object.keys(this.v1obj).map(id => ({ id, name: this.v1obj[id] }))
}
}
Then you can use methods like Object.prototype.hasOwnProperty() to check for existing keys...
methods: {
pushUnique () {
let id = 1
let name = 'josh'
if (!this.v1obj.hasOwnProperty(id)) {
this.v1obj[id] = name
}
}
}
uses vue 2.1.10 vue-resource 1.3.4 to fetch the data:
const app = new Vue({
el: '#UserController',
data:{
users : [],
},
methods:{
fetchUser: function(){
this.$http.get('http://localhost:8000/api/api/users', function(data){
this.$set('users',data)
})
}
},
mounted(){
this.fetchUser()
}
});
but in the end
users has no value.
Vue-resource is a promise based API.
The syntax for the get request should be
this.$http.get('/someUrl')
.then(response => {
// get body data
this.someData = response.body;
}, err => {
// error callback
});
Since you have initialized users: [ ] in the data option , no need to use Vue.$set you can directly assign the value using this.users = data
So do it like this:
fetchUser: function(){
this.$http.get('http://localhost:8000/api/api/users')
.then((data) => {
this.users = data;
}, err => {
// handle error
})
}
const app = new Vue({
el: '#UserController',
data:{
users : [],
},
methods:{
fetchUser: function(){
var self = this;
this.$http.get('http://localhost:8000/api/api/users', function(data){
self.$set(self,'users',data)
})
}
},
mounted(){
this.fetchUser()
}
});
Check variable scope. Set pointer to "this" like "self".
I'm trying to build a small application in VueJs,
Following is my data set:
data(){
return {
pusher: '',
channel:'',
notify: [],
notifications: '',
notificationsNumber: '',
}
},
where I'm having an axios call in created property of components as:
axios.get('api/notifications', {headers: getHeader()}).then(response => {
if(response.status === 200)
{
this.notify = response.data.notifications
this.notificationsNumber = this.notify.length
}
}).catch(errors => {
console.log(errors);
})
I'm having pusherJs implemented, so I'm having following code:
this.pusher = new Pusher('xxxxxxxx', {
cluster: 'ap2',
encrypted: true
});
var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
console.log(data.notification);
that.notifications = data.notification
});
Once the value is being obtained from pusher I want to push this to my array notify as watch property, something like this:
watch: {
notifications(newValue) {
this.notify.push(newValue)
this.notificationsNumber = this.notificationsNumber + 1
}
}
So the problem is the data format which I'm receiving through pusher is in object form and push function is not getting implemented in this:
Screenshot:
Help me out with this.
I'm making an assumption that response.data.notifications is an Array Like Object.
So all you have to do is:
this.notify = [...response.data.notifications];
Vue 2.2.6 version is used.
I have built very simple Vue instance and I want it to return the list of employees names. But the problem is that after getting /employees.json employees data is not being updated. I tried to debug it with console.log and it shows that inside loadData() function employees data is set correctly. But after this function is executed employees value becomes empty again.
var employees = new Vue({
el: 'employees',
template: "<ul id='employees'><li v-for='employee in employees'>{{ employee['name'] }}</li></ul>",
data: {
employees: []
},
methods: {
loadData: function () {
this.$http.get('/employees.json').then(response => {
this.employees = response.body;
//1. console.log returns here ">employees: [object Object]"
});
}
},
mounted: function (){
this.loadData();
//2. console.log returns here empty employees value
}
})
Where am I wrong? How correctly assign value from /employees.json to employees variable?
The console.log in mounted will return empty because the loadData is asynchronous, and will not have completed.
Your el isn't going to work because it needs a #: '#employees'
The template isn't going to work inline like that, because templates are for components. Where would it put it?
var employees = new Vue({
el: '#employees',
data: {
employees: []
},
methods: {
loadData: function () {
setTimeout(() => {
console.log('setting');
this.employees = [{name:'one'},{name:'two'}];
}, 800);
/*this.$http.get('/employees.json').then(response => {
this.employees = response.body;
//1. console.log returns here ">employees: [object Object]"
});*/
}
},
mounted: function (){
this.loadData();
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<ul id='employees'><li v-for='employee in employees'>{{ employee['name'] }}</li></ul>
I want to use a function as a data property. This seems to work fine as in the case of the 'works' data property. However I need the this context in the function so that I can calculate values stored in the this.shoppingCart (another property).
Is this possible? If so what am I doing wrong?
new Vue({
el: '#vueApp',
data: {
shoppingCart: [],
works : function () {
return "testfunc";
},
totalPriceCalcProperty : function () {
this.totalPrice = this.shoppingCart.reduce(function(total, cartItem){
console.log(total, cartItem);
return total + parseFloat(cartItem.price);
}, 0);
}
},
methods: {
totalPriceCalc: function () {
this.totalPrice = this.shoppingCart.reduce(function(total, cartItem){
console.log(total, cartItem);
return total + parseFloat(cartItem.price);
}, 0);
},
}
You should implement this by using methods, not data.
data is helping you to store something rather than handle some actions.
In methods, you can call this.xxx to get the properties from data or property