I am new to Vue 3 and whilst I use Javascript regularly I am not an expert at it. In my Vue 3 project, I found (not on SO) a solution to a particular challenge to deploy Stripe's paymentRequest method. I got the example code to work, but it only works properly when wrapped within this (to me) strange void function construct. However, when wrapped in this construct, I can no longer access variables otherwise available through the 'this' object, so outside the function I can access 'this.myVar' inside I can't.
I found a solution to this but it feels clunky and I am sure there is a better way. The clunky way is to assign any 'this' variables to global javascript variables (within the script tag) just before this construct runs - it works, but doesn't feel the best way by a long stretch. Here is the code in example form...
<script> //section of Vue
var myVar = "";
export default {
name: 'myVueScreen',
data() {
return {
myVar: "foo",
},
}
methods: {
myMethod() {
console.log(this.myVar); //prints 'foo'
myVar = this.myVar;
console.log(myVar); //prints 'foo'
// strange function construct... what is this??
(function () {
console.log(myVar); //prints 'foo'
console.log(this.myVar); fails with this.myVar undefined
})(); // I really don't understand the role of the 'extra' ()
}
}
}
Can anyone tell me what's actually going on with this (function () {.. construct, why 'this.myVar' is outside scope somehow and therefore failing as undefined, and whether there is a way to pass 'this.myVar' to it without using global JS variables as I currently am... thanks!
BTW, I did find that you can pass variable values into this function as follows, BUT this approach still cannot see 'this.myVar'
So this works...
(function (bar = "foo") {
console.log(bar); //prints 'foo'
...
..and this doesn't, it fails at the first point it tries to read this.myVar:
(function (bar = this.myVar) { //fails here when reading 'this.myVar'
console.log(bar); // never reaches this
...