VueJS - Access to Store data from mounted method? [duplicate] - vue.js

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I'm trying to get access to my store data from a mounted method of my component. It works fine if I try it with a not mounted method. After I read a bit it makes sense that I've no access, but is there any other way I didn't find yet?
methods: {
testEvent() {
// works
let players = this.$store.state.players;
console.log(players);
},
socketEvent() {
// Uncaught TypeError: Cannot read property 'state' of undefined
socket.on('dice_data', function(data) {
let players = this.$store.state.players;
console.log(players);
});
}
},
mounted() {
this.socketEvent()
}
Thank you

Issue is with this inside function
You can solve like this:
socketEvent() {
socket.on('dice_data', (data) => {
let players = this.$store.state.players;
console.log(players);
});
}
or if you prefer to write function, instead of arrow function you can also do like this:
socketEvent() {
let self = this
socket.on('dice_data', function(data) {
let players = self.$store.state.players;
console.log(players);
});
}

Related

How to access "this" from Uppy's callback event

I'm using the Uppy Vue component library, and following the docs, I've initialized Uppy by adding it as a computed property.
computed: {
uppy: () => new Uppy({
logger: Uppy.debugLogger
}).use(AwsS3Multipart, {
limit: 4,
companionUrl: '/',
}).on('complete', (result) => {
this.testing = 'success';
console.log('successful files:', result.successful);
console.log('failed files:', result.failed);
}),
}
I'm trying to update my Vue component's data now by using Uppy's complete event, but "this" is not defined. I'm not quite sure how to access "this" from here.
Any idea how to go about doing this?
Update
After posting this, I found a solution that works. I'm hesitant with this solution though as it seemed too easy.
If no one provides a better solution, I'll add this as the answer.
// Uppy Instance
uppy: function() {
return new Uppy({
logger: Uppy.debugLogger
}).use(AwsS3Multipart, {
limit: 4,
companionUrl: '/',
}).on('complete', (result) => {
this.testing = 'success';
console.log('successful files:', result.successful);
console.log('failed files:', result.failed);
})
},
By following the Uppy docs and instantiating the Uppy instance with an arrow function, this no longer seems to refer to the Vue. This makes it so that accessing this.method(), or this.variable, etc. no longer works.
My solution was to change the Uppy instantiation from an arrow function to a regular function. I believe this causes this to refer to the global instance, but I don't have a solid understanding of this, so take what I say with a grain of salt.
I changed this:
computed: {
uppy: () => new Uppy()
}
To this:
computed: {
uppy: function() { return new Uppy() }
}

How are Data object variables available in mount hook in vue? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
I have vue2 component where I want to access a data object variable to use in template. Pertinent code:
Template:
<div v-html="theWivesBios[currentWife]" class="modal-content"></div>
Script:
export default {
name: "theSixWives",
data() {
return {
theWivesBios: theWivesBios,
currentWife: ""
};
},
mounted() {
elContainer.addEventListener("click", function(ev) {
//Want to manipulate this.currentWife in callback
this.currentWife = "testing"; // this.currentWife isnt available to vue instance
}
What would be best way to "hoist" this.currentWife so the vue instance would have access to it for use in my template?
You have to use an arrow function like this:
export default {
name: "theSixWives",
data() {
return {
theWivesBios,
currentWife: ""
};
},
mounted() {
elContainer.addEventListener("click", () => {
this.currentWife = "testing";
});
}
}
This answer explains very well how this works on regular and arrow functions:
https://stackoverflow.com/a/20279485/7699022
Hope it helped!

Nuxt - How to call a getters in a global mixins?

Hi everyone here is the mixin code I wrote as I want to use this for default.vue and error.vue layout. I am trying to avoid duplicating code in two layout.
export default {
provide () {
return {
copyRight: this.getCopyrightText,
email: this.getEmail,
socials: this.getSocials
}
},
computed: {
getMenu () {
return this.store.getters['general/getMenu'].menu
},
getSocials () {
return this.store.getters['general/getSocialDetails']
},
getCopyrightText () {
return this.store.getters['general/getCopyRight']
},
getEmail () {
return this.store.getters['general/getEmail']
}
},
middleware: 'load-menu-items'
}
This is what I get: Cannot read property 'length' of undefined
What am I doing wrong?
In your component I assume you're using .length on the data you're receiving from the getter method, which is probably where the error occurs.
First of all you should debug to see if your getter is actually working as expected. Try this and look at output in console for every getter computed property. If undefined is printed to the console you'll get the error you posted if you're using .length on it
getEmail () {
let data = this.store.getters['general/getEmail'];
console.log(data);
return data;
}
If you post the component which is using this mixin maybe I can help you further.

Mounted hook running before Created data api is finished loading

I am trying to load a function when images from a data api are finished loading. However, it looks like the function is run before the ApiService is finished and thus the TiffParser.replaceIMG() function is not working properly
Here's my setup:
data: function() {
return {
images: null,
imageLink: apiService.imgSrc,
loading: true,
errored: false
};
},
created: function() {
// fetch the data when the view is created and the data is
// already being observed
apiService
.getImages(this.$route.params.id)
.catch(error => {
console.log(error);
this.errored = true;
})
.then(response => {
this.loading = false;
this.images = response.data;
});
},
//vue js provides us `mounted()`. This means `onload` in javascript
mounted: function() {
TiffParser.replaceIMG();
}
Is mounted the correct lifecycle hook for this task?
You can create a watcher for your images.
created() {
const unwatch = this.$watch('images', function(newValue = [], oldValue = []) {
// any code here will execulte once the value of `images` changes
TiffParser.replaceIMG();
unwatch(); // remove the watcher
// Note that you cannot use ES6 arrow functions here, since arrow functions
// are bound to the parent context, and the `this` keyword
// would then not be bound correctly to the Vue instance.
});
// fetch images
}
Is mounted the correct lifecycle hook for this task?
Yes, if you need to access or modify the DOM of your component immediately before or after the initial render.
However, images would be empty when it's first mounted so using a watcher instead of the mounted hook seems more appropriate for this use case.

How to update component data after calling mounted function? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I'm trying to update my component's data after calling an API (calling method from mounted function)
axios.get("getInfo")
.then(function(res){
this.result = res.data.result
}).catch(function(err){
console.log(err)
})
however the "this.result = res.data.result" doesn't get executed but when i paste the same line before the call, I get result updated (like this.data.result = 20). Also when I try the console.log(res.data) I get no response
I also get the message on the console that the request was completed
XHR finished loading: GET "http://app/getInfo".
My mounted function is like this
mounted:function(){
this.setData()
},
methods:{
setData:function(){
console.log(this.pullData())
},
}
What am I doing wrong? Thanks in advance
You need to store the reference to the component in a variable firstly, then refer to it in the function with the variable instead of this keyword; The reason is that you created a new function in then, this thus refers to the function instead of the Vue component:
var ref = this;
axios.get("getInfo")
.then(function(res){
ref.result = res.data.result
// ^^^ ref instead of this
}).catch(function(err){
console.log(err)
})
And another more straight forward way to do this is to use arrow function which doesn't have a this context:
axios.get("getInfo").then(res => { // arrow function instead of anonymous function
this.result = res.data.result
}).catch(err => {
console.log(err)
})