programing

Vue j spread 구문과 Vuex 사용

goodcopy 2022. 8. 30. 23:54
반응형

Vue j spread 구문과 Vuex 사용

vuex mapState를 사용할 때 문서에는 다음과 같이 확산 구문을 사용할 수 있다고 나와 있습니다.이 구문은 의도대로 동작하고 있습니다.

이것이 실제로 어떤 역할을 하는지 궁금할 뿐이므로 확산 구문을 사용하는 방법을 더 잘 이해할 수 있습니다.

이게...

computed: {
  ...mapState([
    'message',
    'storeArray'
  ])
}

효과적으로 이 일을...?

computed: {
  message(){
    return this.$store.state.message
  }
  storeArray(){
    return this.$store.state.storeArray
  }
}

네.

뭐?mapState함수와 함께 오브젝트를 반환하는 것이므로 실질적으로 오브젝트는 반환됩니다.

{ 
  message(){
    return this.$store.state.message
  }
  storeArray(){
    return this.$store.state.storeArray
  }
}

또는 실제로

{ 
  message: function(){
    return this.$store.state.message
  }
  storeArray: function(){
    return this.$store.state.storeArray
  }
}

그건 똑같아요.

확산 연산자는 객체 키를 추출하여 상위 객체에 배치하고 동일한 이름의 기존 키를 바꿉니다.

즉, 기본적으로 다음과 같습니다.

computed: {
  message: mapState(['message','storeArray'])['message'],
  storeArray: mapState(['message','storeArray'])['storeArray']
}

확산 연산자를 사용하는 것이 더 쉬운 방법이라고 생각할 수 있습니다.Object.assign.

computed: {...mapState(...), ...myOtherComputedObject)
computed: Object.assign({}, mapState(...), myOtherComputedObject)

공식 문서에서 말하는 바와 같이:

mapState는 개체를 반환합니다.다른 로컬 계산 속성과 조합하여 사용하는 방법은 무엇입니까?일반적으로는 유틸리티를 사용하여 여러 개체를 하나로 병합해야 최종 개체를 계산에 전달할 수 있습니다., 오브젝트 확산 연산자(4단계 ECMAScript 제안)를 사용하면 구문을 대폭 간소화할 수 있습니다.

 computed: {
    localComputed () { /* ... */ },
    // mix this into the outer object with the object spread operator
    ...mapState({
      // ...
    })
  }

이 구문은 단순화하고 깨끗한 코드를 제공하기 위해 사용되며 로케일을 사용할 때도 필요합니다.computed특성.

, 이 논의는 관련이 있어요

Object.assign()을 사용하면 상세 구문을 쉽게 읽을 수 없습니다.

대체 접근법은 최근에 JavaScript 사양에 추가된 개체 확산 구문을 사용하는 것입니다.spread (...) 연산자를 사용하여 열거 가능한 속성을 한 개체에서 다른 개체로 보다 간결하게 복사할 수 있습니다.

언급URL : https://stackoverflow.com/questions/53913483/vue-js-spread-syntax-with-vuex

반응형