鍍金池/ 問答/HTML/ 關于vue組件中this的一個小白問題

關于vue組件中this的一個小白問題

如以下代碼所示,在組件生命周期hook函數(shù)內獲取的this與在組件的某個事件處理程序種返回的this具有顯著的區(qū)別。
當我在created方法中打印this時,系統(tǒng)顯示this是一個VueComponent, 有所有與組件相關的信息:

clipboard.png

而在組件某個元素進行點擊后,事件處理程序中返回的this,則只是一個對象,僅包含有限信息:

clipboard.png

所以想請教一下vue中this綁定的機制是怎樣的?

代碼如下:

<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>
回答
編輯回答
焚音

這個不是 Vue 的問題,是你自己代碼的問題。你仔細看一下你自己的代碼,鉤子函數(shù)那里,createdmounted 都是普通聲明方式;而事件處理函數(shù)那里,則是用的箭頭函數(shù)。箭頭函數(shù)會固定把 this 綁定到執(zhí)行時的上下文,所以兩者出現(xiàn)了差異。

所以,Vue 組件的函數(shù)要避免使用箭頭函數(shù),Vue 會幫助你把 this 處理到當前實例上。

2018年1月27日 09:10