반응형
Vuex 상태의 어레이 항목 복제(Socket.io 사용)
이 앱은 Vue에 내장되어 있으며 Vuex를 사용하고 있습니다.소켓을 사용하여 노드/Express 백엔드에 연결합니다.필요할 때 서버에서 클라이언트로 데이터를 즉시 푸시할 수 있습니다.
클라이언트에 푸시된 데이터는 VUEX의 배열에 저장되는 개체 형식입니다.어레이에 푸시된 각 데이터 개체에는 고유한 문자열이 연결되어 있습니다.
이 문자열은 VUEX의 어레이에 이미 푸시된 개체를 비교하는 데 사용됩니다.중복된 항목이 있으면 저장되지 않습니다.같지 않은 경우 =가 저장됩니다.
그 후, 나는...mapGettersVuex에서 어레이를 가져와 루프를 통과합니다.각 오브젝트에 대해 컴포넌트가 렌더링됩니다.
단, VUEX의 어레이에 1개의 복사본만 표시되어도 같은 오브젝트가 2회 렌더링되는 경우가 있습니다.
VUEX 스토어의 코드는 다음과 같습니다.
export default new Vuex.Store({
state: {
insiderTrades: [],
},
mutations: {
ADD_INSIDER_TRADE(state, insiderObject) {
if (state.insiderTrades.length === 0) {
// push object into array
state.insiderTrades.unshift(insiderObject);
} else {
state.insiderTrades.forEach((trade) => {
// check if the insider trade is in the store
if (trade.isin === insiderObject.isin) {
// return if it already exists
return;
} else {
// push object into array
state.insiderTrades.unshift(insiderObject);
}
});
}
},
},
getters: {
insiderTrades(state) {
return state.insiderTrades;
},
},
다음은 앱에 있는 코드입니다.표시하다
mounted() {
// //establish connection to server
this.$socket.on('connect', () => {
this.connectedState = 'ansluten';
this.connectedStateColor = 'green';
console.log('Connected to server');
});
//if disconnected swap to "disconneted state"
this.$socket.on('disconnect', () => {
this.connectedState = 'ej ansluten';
this.connectedStateColor = 'red';
console.log('Disconnected to server');
});
// recieve an insider trade and add to store
this.$socket.on('insiderTrade', (insiderObject) => {
this.$store.commit('ADD_INSIDER_TRADE', insiderObject);
});
},
당신의.forEach기존 항목을 반복하고 모든 기존 항목에 대해 새 항목을 한 번 추가합니다.사용방법:
ADD_INSIDER_TRADE(state, insiderObject) {
const exists = state.insiderTrades.find(trade => trade.isin === insiderObject.isin);
if (!exists) state.insiderTrades.unshift(insiderObject);
},
이니셜은 필요 없습니다.length확인.
언급URL : https://stackoverflow.com/questions/66567013/duplicate-array-items-in-vuex-state-using-socket-io
반응형
'itsource' 카테고리의 다른 글
| Alarm Manager 예시 (0) | 2022.08.31 |
|---|---|
| Safari 폭(%) 계산이 잘못됨(부모로부터 1px 필러). (0) | 2022.08.31 |
| Vuetify v-data-table 고정 헤더가 작동하지 않음 (0) | 2022.08.31 |
| Intelij에서 디버깅을 할 때 반환값을 알 수 있습니까? (0) | 2022.08.31 |
| vuex-module-decorator에서 재사용 가능한 getter 생성 (0) | 2022.08.31 |