This in all the places. .... Vue 2 style.
<script>
export default {
data: vm => ({
badData: this.badMethod(), // this = window
goodData: vm.goodMethod() // vm = vue component
}),
computed: {
badComputed: () => this.badData, // this = window
goodComputed: vm => vm.goodData, // vm = vue component
goodComputed2 () {
console.log(this) // vue component
}
goodComputed3: function () {
console.log(this) // vue component
},
goodComputed4: {
get: vm => vm.goodData, // vm = vue component
set(val) {
this.goodData = val // this = vue component
}
}
},
methods: {
badMethod: () => {
console.log(this) // window
},
goodMethod () {
console.log(this) // vue component
},
goodMethod2: function () {
console.log(this) // vue component
},
// Function doesn\'t reference \"this\", so an arrow function is fine here.
doesntMatter: () => 1 + 1
},
created () {
// BAD
// The \"function\" keyword affects the value of \"this\".
axios.get().then(function (response) {
console.log(this) // window
})
// GOOD
// An arrow function causes the function to inherit the \"this\" value from the
// parent scope, in this case, the scope of the created() function.
axios.get().then(response => {
console.log(this) // vue component
})
// GOOD
// Prefer arrow functions, but saving the value of \"this\" in a higher scope will also work.
const self = this
axios.get().then(function (response) {
console.log(this) // window
console.log(self) // vue component
})
// BAD
// Obviously this doesn\'t just apply to axios callbacks, it applies to any callback.
setTimeout(function () {
console.log(this) // window
}, 0)
// GOOD
setTimeout(() => {
console.log(this) // vue component
}, 0)
// You can avoid some of these \"gotchas\" with async/await, refer to the
// fetchData() method in the earlier \"Async calls\" section.
},
}
</script>