How to fetch data from server in vue js? - javascript

I am trying to fetch data from the server using Vue + Vuex + Vue resource.On button click I want to hit Http request and show in list format .I tried like that.Here is my code
https://plnkr.co/edit/EAaEekLtoiGPvxkmAtrt?p=preview
// Code goes here
var store = new Vuex.Store({
state: {
Item: []
},
mutations: {
getItems: function (state) {
}
},
actions: {
fetchData:function (context) {
this.$http.get('/data.json', function(v1users)
{
// this.$set('v1_user',v1users);
});
}
}
})
var httprequest = Vue.extend({
"template": '#http_template',
data: function () {
return {
items: store.state.Item
}
},
methods: {
fetchData: function () {
store.dispatch('fetchData')
},
}
})
Vue.component('httprequest', httprequest);
var app = new Vue({
el: '#App',
data: {},
})
;
any udpdate?

Try using Vue.http.get instead of this.$http.get.
Vuex doesn't have access to $http directly from instance.

Related

Vue returning data objects from axios call to controller

I'm using vue in laravel and trying to get a controller function that I'm hitting to return the data so that I can use it in the data() section of my vue template.
I know the controller function returns what I need, but I'm not so sure how I need to handle the return/response in the axios call in order to start placing the data into the data() function in vue
Blade/Vue template
import moment from 'moment'
export default {
name: 'calendar',
data () {
return {
events: [
{
title: 'test',
allDay: true,
start: '2019-08-17',
},
],
config: {
defaultView: 'month',
eventRender: function(event, element) {
console.log(event)
}
},
}
},
created() {
this.fetchTasks();
},
methods: {
fetchTasks() {
axios.get('/landing/tasks' )
.then((response) => {
// handle success
this.assetOptions = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
});
}
}
}
Route
Route::get('/landing/tasks', 'landingController#getTasks')
->name('landing/tasks');
Controller
public function getTasks()
{
$getTask = Task::getTaskForLanding();
$result = array();
foreach($getTask as $id => $task){
$result[$task->taskt_id][] = $task;
}
}
If you are certain that the Controller returns what you need, the only thing you are missing is declaration of assetOptions. To be able to assign response.data to assetOptions later on, you have to declare it in the data function first.
data() {
return {
...
assetOptions = []; // assuming you are expecting an array
...
};
}
Once that is done, you are all set.

How to update data in Vuejs?

I want to display the updated data in the modal. There is a click function which trigger the testing(data) function below.
The data comes out right in the function. However, the template doesn't seem to update, it still displays the previous data. How can I fix this?
Script:
function testing(data) {
const testingLink = new Vue ({
el: '#test',
data: { selected: data },
methods: {
showDialog: function() { $("#test).modal() }
}
})
testingLink.showDialog()
}
You shouldn't create a Vue Instance in a repeatable function
Try it in following way:
const testingLink = new Vue ({
el: '#test',
data: { selected: null },
methods: {
showDialog: function(data) {
this.selected = data
$("#test").modal()
}
}
})
testingLink.showDialog(YOUR_DATA_YOU_WANT_TO_PASS)

Using vue-resource in a plugin

I am trying to put all my vue-resource requests into a separate component/plugin for easy re-use and no duplication, but being new to Vue I am not sure if this is the correct approach.
It seems a little clumsy.
I want to be able to define all my resources in my plugin as well as be able to initialize new sessions and setup the Auth header globally. The following works but I am sure there is a better/cleaner way.
Would appreciate any guidance/advice on the better approach here.
Thanks
Plugin - DataService.js
Created an Init function to setup the global Auth header and then some other properties to store paths and options.
const DataService = {
init : function(newsession) {
this.session = newsession;
Vue.http.headers.common['Authorization'] = newsession;
},
userpath : '/api/users/',
options: {emulateJSON: true},
};
DataService.install = function (Vue, options) {
Vue.prototype.$getUser = function (userid) {
return this.$http.get(DataService.userpath + userid);
}
Vue.prototype.$saveUser = function (user) {
return this.$http.post(DataService.userpath + user.id,{data: user},DataService.options);
}
}
Vue Instance - account.js
Note: I am first initializing my DataService to pass in the new session as well as call it as a Plugin (.use).
DataService.init(session_id);
Vue.use(DataService);
new Vue({
el: '#app',
data: {
user: { id: null, username: null},
session: { },
processing: false,
alert: "",
warning: "",
},
computed: {
},
mounted: function() {
this.loadUser();
},
methods: {
loadUser: function () {
this.$getUser(userid).then(function(response) {
// get body data
var res = response.body;
this.user = res.data;
this.session = res.session;
}, function(response) {
console.error('Error loading user',response);
});
},
saveUser: function () {
this.$saveUser(this.user).then( function(response) {
// success callback
console.log('Saved user',response);
}, function(response){
// error callback
console.error('Error Saving user',response);
});
}
}
});

Add custom property to vuejs component

How do I set a custom property inside a vue component?
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
// This does not seem to work
this.item.customProperty = 'customProperty';
}
});
You can use Vue.set to add reactivity:
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
Vue.set(this.item, 'customProperty', 'customProperty');
}
});
It seems that you should use Object.assign:
var myComponent = Vue.extend({
data: function() {
return {
item: {}
}
},
created: function() {
// This does not seem to work
this.item = Object.assign(this.item, {customProperty:'customProperty'});
}
});

How do I pass a dynamic page :id to $http.get url in Vue.js

I have have view router set up:
router.map({
'/tracks/:id': {
component: SingleTrack
}
})
And this is my component (which works with a hard coded URL):
var SingleTrack = Vue.component('track', {
template: '#track-template',
data: function() {
return {
track: ''
}
},
ready: function() {
this.$http.get('//api.trax.dev/tracks/1', function (data) {
this.$set('track', data.track)
})
}
});
How do I pass the url/:id to the end of the $http.get string so i can grab the correct data dynamically when that route in loaded, something like:
ready: function(id) {
this.$http.get('//api.trax.dev/tracks/' + id, function (data) {
this.$set('track', data.track)
})
}
You should be able to get the route parameter from the component $route property :
var itemId = this.$route.params.id;
this.$http.get('//api.trax.dev/tracks/' + itemId, function (data) {
this.$set('track', data.track)
})
See more details in vue.js router documentation
For Best Practises:
index.js(router)
{
path: '/tracks/:id',
name: 'SingleTrack',
component: SingleTrack,
props: (route) => {
const id = Number.parseInt(route.params.id);
return { id }
},
}
SingleTrack.vue
props: {
id: {
type: Number,
required: true,
},
},
mounted(){
this.$http.get('//api.trax.dev/tracks/' +this.id, function (data) {
this.$set('track', data.track)
})
}

Categories