2016-08-30 119 views
0

我已經使用vue-router爲一個簡單的事件系統設置了一個組件系統。我希望能夠使用相同的組件來編輯現有事件和創建新事件。重用Vue組件,刪除數據

我想不出如何從編輯一個事件導航到創建另一個事件時從組件中刪除數據。

我曾嘗試下面的東西,它不工作:

  • 設置EVENTID:空在V-LINK
  • 設置EVENTID通過爲空V系列:點擊
  • 設置EVENTID與:this。$ route.params.eventId

路由器映射:create和eventDashboard路由指向同一個組件。

router.map({ 
'/': { 
     name: 'calendar', 
     component: Vue.component('calendar'), 
     subRoutes: { 
      '/rightView': { 
       name: 'rightView', 
       component: Vue.component('rightView'), 
      }, 
     }, 
    }, 
'create': { 
     name: 'create', 
     component: Vue.component('create'), 
     subRoutes: { 
      '/rightView': { 
       name: 'rightView', 
       component: Vue.component('rightView'), 
      }, 
     }, 
}, 
'eventdashboard/:eventId': { 
     name: 'event', 
     component: Vue.component('create'), 
     subRoutes: { 
      '/rightView': { 
       name: 'rightView', 
       component: Vue.component('rightView'), 
      }, 
     }, 
}, 
}) 

這裏是用來創建一個新的事件的按鈕:

<a v-link="{name: 'create', params: { eventId: null }, replace: true}" class="btn btn-success"><i class="fa fa-plus"></i> Create New Event</a> 

和組件:

Vue.component('create', 
{ 
template: '#create', 
data: function(){ 
    return { 
     eventId: this.$route.params.eventId, 
     event: [] 
    } 
}, 
ready: function() { 

    this.getEvent(); 
}, 

methods: { 
    getEvent: function(eventId){ 
     var getList = this.$http.get('event/'+this.eventId) 
      .success(function(data){ 
       this.event = data; 
      }.bind(this)); 
    }, 
    } 
}); 

回答

1

請參考VUE的路由器數據鉤明白這一點。 http://router.vuejs.org/en/pipeline/data.html

當路由發生變化並且當前組件被重用時,會調用數據轉換掛鉤。

您可以將您獲取數據的邏輯傳遞給數據轉換鉤子,並根據路由是否具有:eventId,您可以決定它是創建頁面還是添加頁面。如果其添加頁面將事件對象重置爲空數組。

Vue.component('create', { 
    template: '#create', 
    data: function() { 
    return { 
     event: [] 
    } 
    }, 
    route: { 
    data: function(transition) { 
     if (transition.to.params.eventId) { //get events data if eventId is present in the route params 
     return this.$http.get({ 
      url: 'event/' + transition.to.params.eventId 
     }).then(function(response) { 
      return { 
      event: response.data 
      } 
     }, function() { 
      console.log('request failed') 
     }) 
     } else { // Its add mode, set event object to empty array 
     setTimeout(function() { 
      transition.next({ 
      event: [] 
      }) 
     }, 1000) 
     } 
    } 
    } 
}); 

而且您的添加按鈕應該是這樣的:

<a v-link="{name: 'create'}" class="btn btn-success"><i class="fa fa-plus"></i> Create New Event</a> 

和編輯應該是:

<a v-link="{name: 'event', params: { eventId: 'Your Event Id'}}" class="btn btn-success"><i class="fa fa-plus"></i> Edit Event</a> 
+0

謝謝你,這是完美的。我曾嘗試過transition.to.params,我認爲我的錯誤是在數據以及路由 - >數據中設置eventId。 – retrograde

+0

@retrograde歡呼! – Deepak