鍍金池/ 問答/HTML/ 此處vue.js的methods中,this[attr]是什么用法

此處vue.js的methods中,this[attr]是什么用法

組件template:

<my-dialog :is-show="isShowLogDialog" @click="closeDialog('isShowLogDialog')">
</my-dialog>

組件引入:

import MyDialog from './base/dialog'

組件data:

data () {
    return {
      isShowLogDialog: false,
    }

組件methods:

 methods: {
    closeDialog (attr) {
      this[attr] = false
 },

請(qǐng)問:這里methods里的this[attr]是什么用法?官方文檔沒找著,這個(gè)this也是指代vue實(shí)例對(duì)象吧

回答
編輯回答
尤禮

thisvue實(shí)例對(duì)象;
template,當(dāng)點(diǎn)擊的時(shí)候,會(huì)觸發(fā)closeDialog('isShowLogDialog'),所以此時(shí)的methods里面的closeDialogattr參數(shù)是'isShowLogDialog',this[attr] = false也就是this['isShowLogDialog'] = false;
因?yàn)?code>template里面:is-show="isShowLogDialog",當(dāng)isShowLogDialog被設(shè)置成false的時(shí)候,也就關(guān)閉了對(duì)話框。

2017年2月20日 04:57
編輯回答
妖妖

this[attr], 其實(shí)是原生js 里面獲取對(duì)象屬性的方法,或者給對(duì)象屬性賦值。
獲取對(duì)象屬性有點(diǎn)方法和中括號(hào)方法.
中括號(hào)法可以用變量作為屬性名,點(diǎn)方法舊不可以,即:

var objVue = {};
objVue.isShowLogDialog  = false;
var arg = 'isShowLogDialog'    // 這里就可以代表傳入的任何參數(shù) 
console.log(objVue.arg)    // undefined
console.log(objVue[arg])   // false;

《高程3》里面 記得推薦使用 點(diǎn)方法,效率高

2018年9月15日 18:23
編輯回答
話寡

這里的attr就是data 對(duì)象的某個(gè)key

比如 問題中的 isShowLogDialog

一般寫成:this.isShowLogDialog=false
但如果這個(gè) attr 想動(dòng)態(tài)傳參,就不能用 . 而只能用[]
于是就只成this[attr]=false;

2017年7月7日 04:35