2017-03-17 43 views
2

我有一個在我的狀態容器數組,我試圖設置一個getter,將其分爲活動和不活動的容器。我使用這個來獲取下面的數組。從獲得者獲取一個選定的屬性

export const x = state => _.partition(state.containers, c => c.state === 'running'); 

這個問題是我想分割並分配給activeContainers和stoppedContainers,然後導出。

[ 
    [ 
    { 
     "id": "1", 
     "name": "test container", 
     "image": "some image", 
     "state": "running", 
     "status": "Running" 
    } 
    ], 
    [ 
    { 
     "id": "2", 
     "name": "another test container", 
     "image": "some image", 
     "state": "stopped", 
     "status": "Running" 
    } 
    ] 
] 

我使用ES6的解構嘗試,但我覺得我失去了一些東西,或將解構在錯誤的地方,它與Vuex工作。

export const [activeContainers = [], stoppedContainers = []] = state => _.partition(state.containers, c => c.state === 'running'); 
+1

您正試圖將一個函數分配給一個數組。這樣做不好。 – Bergi

+0

我只想導出_.partition的結果,而不是返回2個數組,我想要一個。我知道有更簡單的方法,我只是想看看是否有可能這樣做。 –

+0

您目前正在導出*函數*'x',而不是'state'對象或'containers'數組。那麼你如何從那裏導出兩個數組? – Bergi

回答

2

getter

返回functions按照意見中的問題去了,這的確是事實,你不能有一個getter映射兩個屬性。閱讀更多你不希望另一次吸氣的activeContainersstoppedContainers

通過您共享link去後,我發現了一種方法,你仍然可以有一些非常接近參數getter

Here你可以看到它的全部效果。

getters = { 
    getContainer: (state) => { 
    const [activeContainer = [], inactiveContainer = []] = _.partition(state.containers, c => c.state === 'running') 
    return (container) => { 
     return (container === 'activeContainer') // returned function 
     ? activeContainer 
     : inactiveContainer  
    } 
    } 
} 

在這個getter中,我返回一個函數,它可以接受參數並獲得與您所期望的非常接近的內容。

+0

這可能是最接近我想要的,因爲我不知道我必須導出一個函數,而不只是一個數組,所以它會接受它。 –

+1

@AlexisTyler這是github問題包含的內容。在你分享的帖子中,我讀到這是一個可取的模式。你也可以編輯問題標題,因爲它不是關於vuex中的解構,而是從getter中獲取選定的屬性。雖然我也想看看是否可以有更靈活的方式來做到這一點。 :) –