this.$http.get seems doesn't work vue-resource - javascript

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".

Related

Access variable value in mounted function vuejs

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
}
},
},
});

vuejs props are undefined after refresh

App.vue
template:
<ResponsiveNavigation
:nav-links="navLinks"
/>
script
data: () => ({
navLinks: []
}),
created: function() {
this.getSocialNetworks();
},
methods: {
getSocialNetworks() {
var self = this;
axios
.get(MY_API_URL)
.then(function(res) {
var fb_url = res.data.data.filter(obj => {
return obj.key === "Social_Facebook";
});
self.navLinks.fb = fb_url[0].defaultValue;
//
var ig_url = res.data.data.filter(obj => {
return obj.key === "Social_Instagram";
});
self.navLinks.ig = ig_url[0].defaultValue;
//
})
.catch(function(error) {
console.log("Error", error);
});
}
}
ResponsiveNavigation.vue:
<a :href="$props.navLinks.fb"></a>
if I console.log the $props.navLinks I have everything stored.
however in the href doesn't work after the FIRST load.
I am fairly sure that this is due to the reactive nature and UNreactive of arrays.
You're not really using an array, but an object
data: () => ({
navLinks: []
}),
to
data: () => ({
navLinks: {
fb:'',
ig:''}
}),
and I think it would setup the reactive props more suitably.
If you need an array, then use array.push() so it can react accordingly. I may also consider moving it to the mounted() method. Finally, you put $props in your code, do you have other props you've not shown us which may be conflicting?

Bad response with axios call in laravel

I'm trying to figure out what's going on here, but I've set my Vue instance to hit an axios call every time a new tag is added. The problem is I keep getting a 400 bad request and I can't figure out why.
When I add a tag and inspect my Vue element, my object is tag_data: "test string". I just want to make the call with "test string" as my data.
Any obvious issues with what I'm doing?
Route
Route::post('tags/save','CampaignsController#saveTags')
->name('tags/save');
Controller
public function saveTags(Request $request)
{
$tagData = $request->tag_data;
$stmt->bindValue(1,$tagData, PDO::PARAM_STR);
$stmt->bindParam(2, $out2, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$stmt->execute();
}
Blade
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
el: "#tagApp",
data() {
return{
value: [],
loading: false,
options: []
}
},
methods: {
read: function(val){
if (val) {
this.loading = true;
this.options = [];
} else {
this.options = [];
}
},
/*Issue is here*/
addTag(newTag) {
const tag = {
tag_data: newTag,
};
this.options.push(tag);
this.value.push(tag);
axios.post('campaigns/tags/save',{
tag_data: newTag,
})
.then(function (response){
console.log(response);
})
.catch(function (error) {
console.log(error);
console.log(tag_data);
});
}
}
})

Vuex how to pass state/getter in data prop

I retrieved my data from database using axios under my vuex
const state = {
giveaways: null
}
const actions = {
getGiveAways : ({commit}) =>{
axios({
url : '/prod/api/thresholds_settings',
method: 'post',
data : {
},
config: 'JOSN'
})
.then(response=>{
if(response.status == 200){
//console.log(response.data.total_giveaways);
commit('SET_GIVEAWAYS', response.data.total_giveaways)
}
})
.catch(error=>{
if(error.response){
console.log('something happened')
}
});
}
}
const mutations = {
SET_GIVEAWAYS : (state, obj)=>{
state.giveaways = obj
}
}
const getters = {
doneGiveAways(state){
return state.giveaways
}
}
In my Dashboard.vue I have
import {mapState,mapGetters} from 'vuex'
export default{
data: () => ({
cards: [],
giveaways: ''
}),
computed:{
...mapState({
Giveaway: state => state.Threshold.giveaways
}),
doneGiveAways(){
return this.$store.getters.doneGiveAways
}
},
ready(){
//giveaways: this.Giveaways
//console.log(this.Giveaways);
},
created(){
const self = this
this.cards[0].result_val = 2
this.cards[2].result_val = 2;
},
mounted(){
this.$store.dispatch('getGiveAways');
console.log(this.giveaways);
}
}
My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways. If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways
I would use Stephan-v's recommendation and delete the local copy of giveaways. But I don't know what your specific reason is for declaring an extra copy of giveaways, so here is a solution that will work:
In your Dashboard.vue add:
export default {
...
watch: {
Giveaway(value) {
this.giveaways = value
}
},
...
}
Just delete the giveaways property from your data Object and rename the computed doneGiveAways to giveaways and you are done.
There is no need for a local component giveaway data property in this scenario.

Why data of the Vue instance is not updated

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>

Categories

Resources