2017-05-14 86 views
1

我想學習vue 2,但我被卡住了,有人可以幫我解釋爲什麼我無法在事件關閉中訪問這個組件? 在控制檯中沒有錯誤認爲它不會呈現爲什麼我無法從閉包訪問vuejs實例變量?

也許無用的信息: 通天的WebPack,VUE裝載機,事件總線的工作雖然不是第一次了,我supose該組件沒有創建依舊,但我認爲這不是真正的問題

<template> 
    <div class="w3-row-padding"> 
     <div class="w3-pannel">{{categoryName}}</div> 
     <categoria-admin v-for="number in 9"></categoria-admin> 
    </div> 
</template> 




<script> 

    import Bus from '../Classes/Bus'; 

    export default { 

     data: function() { 
      return { 
       //Bind vari to template doesn't work either 
       vari: "varivari" 
      }; 
     }, 
     //tried with oncreate too 
     mounted: function() { 
      this.vari = "foo";//it works 
      // I tried with es5 passing this through a variable, doesn't work either 
       Bus.$on('categoria-item-selected', (category) => { 
        console.log("entering closure");// this get printed 
        this.vari = "ha funcionado" // doesn't work 
        this.updateVari('ha funcionado');// doesnt work 
        console.log(this.vari); // prints ha funcionado , but in template 
              //is not reflected and with chrome tool either 
       }); 
     }, 
     computed: { 
      categoryName : function() { 
       return this.vari; 
      } 
     }, 
     methods: { 
      updateVari: function (value){ 
       this.vari = value; 
      } 
     } 


    } 
</script> 
+0

巴士是什麼?它是一個Vue對象嗎?如果你在事件處理程序中使用console.log(this),它會記錄什麼? – Bert

回答

0

我不能再現它。你的代碼似乎很好地工作:

(點擊一個按鈕發出的事件,那麼變量將改變 - 上述按鈕通知文本)

const bus = new Vue({}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    foldersList: [{id: 1, name: 'first'}, {id: 2, name: 'second'}], 
 
    foldersStatus: true 
 
    }, 
 
    methods: { 
 
    emitMe: function() { 
 
    bus.$emit('myevent'); 
 
    } 
 
    }, 
 
    components: { 
 
    'child' : { 
 
     template: `<p>{{ vari }}</p>`, 
 
     data: function() { 
 
     \t return { 
 
      vari: 'varivari' 
 
     } 
 
     }, 
 
     mounted() { 
 
     \t this.vari = "foo"; 
 
     bus.$on('myevent', (category) => { 
 
      console.log("entering closure");// this get printed 
 
      this.vari = "ha funcionado"; 
 
     }) 
 
     } 
 
    } 
 
    } 
 
});
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 

 
<div id="app"> 
 
    <child></child> 
 
    <button @click="emitMe()">Emit</button> 
 
</div>

通常,當您遇到這樣的問題,你應該將當前的this保存到這樣一個變量:const self = this並在異步回調等中引用self。但在這種情況下,它似乎工作正常,this保持不變。