简体   繁体   English

ajax 加载后重新初始化 Vuejs2

[英]Re-initialise Vuejs2 after ajax load

Have looked around and can't find a solution for this.环顾四周,找不到解决方案。

I have a .vue file which is loaded on a page, and the user can click a button which causes an ajax load on the page which replaces some content (including where the vue component is displayed).我有一个加载在页面上的 .vue 文件,用户可以单击一个按钮,该按钮会导致页面上的 ajax 加载替换一些内容(包括显示 vue 组件的位置)。

The ajax call happens outside of Vue, replacing content which includes the vue component. ajax 调用发生在 Vue 之外,替换了包含 Vue 组件的内容。

Once the ajax completes, the Vue component doesn't display. ajax 完成后,Vue 组件不会显示。 Is there a way I can manually re-initialise Vue?有没有办法可以手动重新初始化 Vue?

Thanks谢谢

It's probably not the best way, but it works just creating a new Vue instance (there might be a reason not to do this, I don't use Vue much).这可能不是最好的方法,但它只是创建一个新的 Vue 实例(可能有理由不这样做,我不太使用 Vue)。

I've done a short test here: https://jsfiddle.net/yazbx35d/我在这里做了一个简短的测试: https ://jsfiddle.net/yazbx35d/

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  }
});

$('#app').empty().append($('<p></p>', {
    text: '{{newMessage}}'
}));

new Vue({
  el: '#app',
  data: {
    newMessage: 'Hello again Vue.js!'
  }
});

From what I understand, you could create a separate Vue instance as an Event Bus , emit an event using it when the ajax call completes.据我了解,您可以创建一个单独的 Vue 实例作为Event Bus ,在 ajax 调用完成时使用它发出一个事件。 Listen for the event inside the component or main Vue instance and update the component.监听组件或主 Vue 实例内的事件并更新组件。

Create the bus:创建总线:

var bus = new Vue()

When your ajax call resolves:当您的 ajax 调用解决时:

bus.$emit('update', 1)

Inside your main Vue instance/component:在您的主要 Vue 实例/组件中:

bus.$on('update', function (id) {
  // ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM