2016-12-04 82 views
1

我有一個vuejs組件,安裝後應顯示從服務器獲取的數據並使用響應來更新數據。當我使用turbolinks時,vue js不更新dom。如何使用turbolinks jquery調用後更新vuejs組件數據

我嘗試了許多不同的方法來做到這一點,但沒有工作=(我最後一次嘗試是這樣的一個:

Vue.component('pf-main-menu', { 
    props: [''], 
    template: '<pf-menu v-bind:links="links"></pf-menu>', 
    data: function() { 
    return { links: [{text: 'teste'}] } 
    }, 
    mounted: function() { 
    this.links = [{text: 'teste 2'}]; <-- This change works 

    $.ajax({ 
     url: '/api/v1/menus/main_menu.json', 
    }).success(function(res) { 
     this.links = [{text: 'teste 3'}]; <-- This change does not work 
    }.bind(this)); 
    } 
}); 

https://gist.github.com/victorlcampos/a8c4f05ab53097e4ac07d5bf8306646e

我已經嘗試過這種方式:

Vue.component('pf-main-menu', { 
    props: [''], 
    template: '<pf-menu v-bind:links="links"></pf-menu>', 
    data: function() { 
    return { links: [{text: 'teste'}] } 
    }, 
    mounted: function() { 
    this.links = [{text: 'teste 2'}]; 
    var self = this; 

    $.ajax({ 
     url: '/api/v1/menus/main_menu.json', 
    }).success(function(res) { 
     self.links = [{text: 'teste 3'}]; 
    }); 
    } 
}); 

回答

0

發生這種情況是因爲您沒有指出正確的範圍,這種更改的範圍在$ .ajax調用中,所以您只需執行如下操作:

mounted: function() { 
    this.links = [{text: 'teste 2'}]; <-- This change works 
    var self = this 
    $.ajax({ 
     url: '/api/v1/menus/main_menu.json', 
    }).success(function(res) { 
     self.links = [{text: 'teste 3'}]; <-- This change does not work 
    }.bind(this)); 
    } 
}); 

您也可以查看我的相似答案here

+0

我更新的問題,我曾嘗試用自己的方式之前=(THX的答案 –

+0

我發現現在的問題是相關的。與turbolinks –

0

根據Vue Docs,您必須使用Vue.set來確保反應行爲。

data: function() { 
     return { 
     menu: { 
      links: [ {text: 'teste'}] } 
     } 
    }, .... 

在阿賈克斯sucess回報:

Vue.set(this.menu, links, [{text: 'teste 3'}]); 

更多Vue Docs

相關問題