On a rookie problem of this in vue components

as shown in the following code, the this obtained within the component lifecycle hook function is significantly different from the this returned by one of the component"s event handlers.
when I print this in the created method, the system shows that this is a VueComponent, with all the component-related information:

clipboard.png

this:

clipboard.png

so what is the mechanism of this binding in vue?

the code is as follows:

<template>
  <div class="hello" @click="clickHandler">
      <el-button type="text" @click="dialogVisible = true"> Dialog</el-button>
      <el-dialog
        title=""
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <span></span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false"> </el-button>
          <el-button type="primary" @click="dialogVisible = false"> </el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
    name: "Main",
    methods: {
        clickHandler: (e) => {
            console.log("vue components:", this, this.globalAttr, e)
        },
        handleClose: (done) => {
            this.$confirm("")
                .then(_ => {
                    done()
                })
                .catch(_ => {})
        }
    },
    created: function () {
        console.log("own created hook running:", this)
    },
    mounted: function () {
        console.log("component mounted:", this)
    },
    data () {
        return {
            dialogVisible: false,
            msg: "Welcome to Your Vue.js App"
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .hello{
      height:100%;
  }
</style>
Mar.04,2021

this is not a problem with Vue, it's a problem with your own code. Take a closer look at your own code. In the hook function, created and mounted are common declarations, while event handlers use the arrow function. The arrow function always binds this to the context of the execution, so there is a difference between the two.

therefore, the functions of the Vue component should avoid using arrow functions, and Vue will help you process this to the current instance.

Menu