-3

I have a vue app that I wish to build as a component so I can use it in another app (non-vue).

I'm using the vue-cli to build: vue-cli-service build --target wc --name my-component 'src/App.vue'

I'm having two issues:

1. When vue-cli compiles the code, I noticed 'this' is getting changed:

In my original code, search method does not use function and so this is not overwritten.

    search(id) {
     // this is not overwritten
    console.log(this.myProp)

Here is the same function in the compiled build: screenshot

Notice they cached this with: var _this = this, however, all my references to this are not changed to _this!

Am I crazy or is this not a huge issue? I'm having to do messy workarounds to get my code to work because of this.

stumped :\

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
tyler-g
  • 509
  • 1
  • 6
  • 15
  • Can you provide full code for `search`, both original and transpiled? Please, post it as text and not image. It's unclear what 2 means exactly. Can you elaborate? These are two unrelated questions, I'd suggest to address them separately. – Estus Flask Jun 06 '19 at 15:35
  • @EstusFlask you're right, I'll edit it to just the one question – tyler-g Jun 06 '19 at 15:42
  • I don't think this is the issue. Babel using `_this` to compile arrow functions to es5, since they have another context. Can u provide some more informations? – Orlandster Jun 06 '19 at 15:44
  • 2
    That it's `_this` in one place doesn't mean that it should be `_this` everywhere else. *I'm having to do messy workarounds to get my code to work* - what does exactly not work? Please, update the question with relevant code. Possibly related question, https://stackoverflow.com/questions/54712662/react-this-is-undefined-in-chrome-developer-tools . – Estus Flask Jun 06 '19 at 16:15
  • "all my references to `this` are not changed to `_this`" In the example you showed there's no *need* to change it to `_this`, because where `this` is used it's still in scope. It would be pretty surprising if the compiler were breaking your code, can you show an example of something that isn't working that you're having to write workarounds for? – Daniel Beck Jun 06 '19 at 16:31

1 Answers1

1

Try using an arrow function to capture this.

search: (id)=> {
     // this is not overwritten
    console.log(this.myProp)
}
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78