我有一个 Vue 组件,它生成一个动态组件,并且在该动态组件中是一个用于进行 Ajax 调用的按钮的单击处理程序。在成功完成 Ajax 调用后,我想通知生成动态组件的组件 Ajax 调用已完成。我怎么做?
有问题的代码的基本结构如下:
<template>
<div>
<!-- Other markup here. -->
<div class="contentPlaceholder">
</div>
</div>
</template>
<script>
export default {
// Props, etc.
data: function () {
return {
// ...
content: 'long-html-string-that-contains-Vue-components'
};
},
mounted: function () {
Vue.component(`content-component`, {
template: `
<div class="content">
${this.content}
</div>
`,
data: function () {
return {
// Local data here.
};
}
methods: {
// Button in this.content markup clicked.
btnCicked: function () {
ajax.post('url', {
// Params
success: () => {
// Want to report back to the parent component
// that we're here now.
}
});
}
}
});
const res = Vue.compile(`
<content-component>
</content-component>
`);
new Vue({
render: res.render,
staticRenderFns: res.staticRenderFns
}).$mount(`.contentPlaceholder`);
}
}
</script>
我最初的想法是this.$emit('btnClicked', 'data-here')
在 Ajaxsuccess
回调中做,但是当我尝试在方法调用的部分或方法调用中附加一个@btnClicked
事件处理程序时,我得到一个 Vue 错误。content-component
template
Vue.component
Vue.compile
基本上,我不知道该怎么做。动态组件中的this
上下文肯定是不同的,所以我不能只是给父组件添加一个数据属性,然后在动态组件的Ajax回调中设置。我试过了,但它不起作用。
我相信有一种简单的方法可以做到这一点,但老实说,我不确定如何做。任何帮助将不胜感激。谢谢你。
编辑:值得注意的是,我试图将动态组件视为父组件的常规子组件。因此,我this.$emit('btnClicked')
在 Ajaxsuccess
回调中添加了一个调用,然后@btnClicked
向content-component
.
也许我只是做错了,但我尝试了以下两种方法:
template: `
<div class="content" @btnClicked="btnClicked">
${this.content}
</div>
`,
// And
const res = Vue.compile(`
<content-component @btnClicked="btnClicked">
</content-component>
`);
但似乎两者都不起作用。谢谢。