【发布时间】:2017-12-18 06:07:50
【问题描述】:
我有一个嵌套组件,子组件应该从主实例接收一个参数,但问题是我必须调用该事件两次才能获取参数。
index.html
<div id="app">
<button @click="displayComponent">Display</button><br/><hr/>
{{ message }}
<mycomponent v-if="showComponent" @hide="hideComponents"></mycomponent>
</div>
code.js
window.bus = new Vue();
Vue.component('mycomponent', {
template: `
<div>
<h3>Im the parent component</h3>
<childcomponent></childcomponent>
<button @click="$emit('hide')">Hide components</button>
</div>
`
});
Vue.component('childcomponent', {
template:`
<div>
<h4>Im the child component</h4>
<p>{{ data }}</p>
</div>
`,
data() {
return {
text: 'Nothing loaded'
};
},
methods: {
test() {
alert('hello');
},
getData(x) {
this.text = x;
}
},
created(){
bus.$on('extraCall', data => {
this.getData(data);
this.test();
});
}
});
const app = new Vue({
el: '#app',
data: {
message: 'hello world!',
showComponent: false
},
methods: {
displayComponent() {
bus.$emit('extraCall', 'this is some extra text');
this.showComponent = true;
},
hideComponents() {
this.showComponent=false;
}
}
});
子组件元素内的文本值设置为默认值,单击“显示”按钮后,它会触发 bus.$emit 并带有一些文本作为参数的 extraCall 事件,这应该会更新文本值,并且它仅在第二次单击“显示”按钮后才会发生。
我错过了什么?
【问题讨论】:
标签: javascript html vue.js event-handling vuejs2