在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 關(guān)于vue組件中this的一個(gè)小白問題

關(guān)于vue組件中this的一個(gè)小白問題

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

clipboard.png

而在組件某個(gè)元素進(jìn)行點(diǎn)擊后,事件處理程序中返回的this,則只是一個(gè)對(duì)象,僅包含有限信息:

clipboard.png

所以想請(qǐng)教一下vue中this綁定的機(jī)制是怎樣的?

代碼如下:

<template>
  <div class="hello" @click="clickHandler">
      <el-button type="text" @click="dialogVisible = true">點(diǎn)擊打開 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('確認(rèn)關(guān)閉?')
                .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>
回答
編輯回答
焚音

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

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

2018年1月27日 09:10