data variable undefined when I use setInterval in vue methods - javascript

when I get a data variables from vue data data is undefined how can I get a variable for realtime exchange in vue methods
export default {
name: 'Chart',
components: {
},
data(){
return {
firstUpdateTime:0,
price:[],
timeLable:[],
maxPrice: 20000,
}
},
methods:{
calculateChart : function(){
var a = 300;
setInterval(() =>
this.firstUpdateTime ++;
a--;
);}, 30000);
}
},
}

Related

Vuex and nested object in computed property causes reactivity problem

I use a vuex store to handle a session and loading default sessions for different pages onCreated hook. Data is changing and most of the time it works fine but now I noticed even though I change the data, the setter / mutation is not called.
session.js (mixin to load default session from main component)
export default {
data () {
return {
defaultSession: {}
}
},
created () {
this.$store.dispatch('session/update', { data: this.defaultSession })
},
computed: {
sessionData: {
get () {
console.log('GETTER')
return this.$store.getters['session/sessionData']
},
set (session) {
console.log('SETTER')
this.$store.dispatch('session/update', { data: session })
}
}
}
}
store
export default {
namespaced: true,
state: {
session: {},
},
getters: {
session (state) {
return state.session
},
sessionData (state) {
return state.session.data
},
},
mutations: {
UPDATE (state, session) {
state.session = session
console.log('[Session] Updated')
}
},
actions: {
update: ({ commit }, data) => {
commit('UPDATE', data)
}
}
defaultSession example (in component)
defaultSession: {
name: '',
viewId: '',
defaultImage: null,
dataTable: [{
title: '',
data: [],
selected: [],
}],
imageTableData: [],
selectedIcons: []
},
So in my component I access <input v-model="sessionData.name"/> for instance, but neither the setter, nor the mutation is called. (The object is quite nested, because I also store table data inside.)
UPDATE (possible workaround):
watch: {
sessionData: {
deep: true,
handler() {
//commit changes here
}
}
}

Vue.js - this.<value>.<value> is undefined

<div class="content-chart">
<chart :type="'line'" :data="lineData" :options="options"></chart>
</div>
Above is the template section for a component and below is the script.
<script>
import Chart from 'vue-bulma-chartjs'
import { Tabs, TabPane } from 'vue-bulma-tabs'
export default {
components: {
Chart
},
data () {
return {
persondata: {},
}
},
mounted () {
let parameter = this.$route.params.id
axios.get('/api' + parameter.toString()).then(response => {
this.persondata = response.data
})
},
computed: {
lineData () {
var sth = this.person.dates['date-values']
return {
labels: [9, 10, 11, 12, 13, 14, 15],
datasets: [{
data: sth,
label: 'Speed',
}]
}
}
}
</script>
So as you see this Vue component renders a chart from Chart.js on the page. The problem is when I get the response from the api and save it to the this.persondata variable, when the component is mounted I get "TypeError: this.persondata.dates is undefined". If I do this though:
data () {
return {
persondata: {
dates: {
'date-values': []
}
}
}
}
and I try to save the response.data.dates['date-values'] to this.persondata.dates['date-values'] and insert it into the dataset.data in computed() I don't get any chart.
What is the problem?
computed properties are calculated right away: they are calculated before your Ajax returns.
Since you only populate persondata when the Ajax returns, the first time the computed is calculated, persondata is {} (the value of initialization in data).
Quick fix: initialize with an empty dates object, so the computation doesn't throw that error (giving time for the Ajax to return, which will update the computed property automatically):
data () {
return {
persondata: {dates: {}}, // added empty dates property
}
},

How to access vuejs method from inside an object ? (Vuejs 2 )

I want to access getValue method from Chart object, but I get function undefined.
<template>
<div>
<canvas width="600" height="400" ref="canvas"></canvas>
</div>
</template>
<script>
import Vue from 'vue';
import Chart from 'chart.js';
import Axios from 'axios';
export default {
mixins: [DateRangeMixin],
props: {
// other props...
callback: false,
},
data() {
return {
chart: '',
};
},
mounted() {
// ...
},
methods: {
//other methods...,
getValue(data) {
if (data === 1) {
return 'Up'
} else if(data === 0) {
return 'Down';
}
},
render(data) {
this.chart = new Chart(this.$refs.canvas, {
type: 'line',
data: {
labels: Object.keys(data),
datasets: [{
// a lot of data ....
data: Object.values(data),
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback(label, index, labels) {
return this.getValue(label); // <-- Tried this and got: 'this.getValue is not a function'. I understand it bounces to new Chart object, but how to resolve this?
}
}
}]
}
}
});
},
},
};
</script>
I understand that it's because Chart is an object and this is pointing to it, but how do I resolve this and access my method from the callback ?
I imagine if that export default... would be set to a variable, then I could access my method via variable.methods.getValue , but in this scenario How can I achieve my goal ?
Right before you create the new Chart() assign this to a variable self: var self = this;.
You can then access your component properties throughself.

How to fetch data from server in vue js?

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.

Cannot add to Vuex store correctly

I have this Vuex 2 store:
const datastore = new Vuex.Store({
state: {
socketcluster: {
connection: false,
channels: []
},
selected_offers: []
},
mutations: {
addOffer: function(offer) {
datastore.state.selected_offers.push(offer) // first problem: cannot just use state.offers as it throws an undefined
}
},
getters: {
getOffers: function(){
return datastore.state.selected_offers;
}
}
});
And inside a Vue 2 component I do:
methods: {
clicked: function(){
console.log("Toggle Offer");
if ( datastore.getters.getOffers.filter(function(o){ o.id == this.offer.id } ).length == 0 ) {
// add it
datastore.commit('addOffer', this.offer)
} else {
// TODO remove it
}
}
}
What happens is that when I trigger the method, the store changes as follows:
What am I doing wrong?
This is a simple way to work with vuex pattern, In big applications you should use actions instead of mutating the state directly from the component "like I did ", if so i urge you to read more about vuex.
const store = new Vuex.Store({
state: {
socketcluster: {
connection: false,
channels: []
},
selected_offers: [ "offer1", "offer2"]
},
mutations: {
addOffer: function( state, offer ) {
state.selected_offers.push(offer);
}
},
getters: {
getOffers: function( state ){
return state.selected_offers;
}
}
});
new Vue({
store,
data: function() {
return {
offer: "offer3"
}
},
methods: {
clicked: function() {
if ( this.offers.length === 2 ) {
this.$store.commit('addOffer', this.offer)
} else {
// TODO remove it
}
}
},
computed: {
offers: function() {
return this.$store.getters.getOffers;
}
}
}).$mount( "#app" );
<script src="https://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>
<div id="app">
<div v-for="offer in offers" > {{offer}}</div>
<button #click="clicked"> clicked </button>
</div>
The first parameter passed to a mutation is the state object. So, you're pushing the entire state object to the selected_offers array.
Your mutation method should look like this:
mutations: {
addOffer: function(state, offer) {
state.selected_offers.push(offer)
}
},
Here's the documentation for vuex mutations.

Categories