我试图学习vue 2,但是我被困了,有人可以帮我解释为什么我无法在事件关闭中访问这个组件吗? 控制台中没有错误认为它没有被渲染
可能没用的信息: Babel,webpack,vue-loader,事件总线工作虽然不是第一次,但我认为该组件仍未创建,但我认为这不是真正的问题
<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 :(得分:1)
我无法重现它。你的代码似乎工作正常:
(单击按钮发出事件,然后变量值将更改 - 通知按钮上方的文本)
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() {
return {
vari: 'varivari'
}
},
mounted() {
this.vari = "foo";
bus.$on('myevent', (category) => {
console.log("entering closure");// this get printed
this.vari = "ha funcionado";
})
}
}
}
});
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<child></child>
<button @click="emitMe()">Emit</button>
</div>
&#13;
通常,当您遇到此类问题时,您应该将当前this
保存到这样的变量:const self = this
并在异步回调等中引用self
但在这种情况下似乎工作正常,this
保持不变。