sourcecode

선택한 Vue.js 옵션이 값을 기반으로 하지 않음

copyscript 2022. 7. 30. 18:17
반응형

선택한 Vue.js 옵션이 값을 기반으로 하지 않음

API 호출에서 다음과 같이 json 개체가 반환되었습니다.

"countries": [
{
  "id": 1,
  "iso": US,
  "name": "United States",
},
{
  "id": 2,
  "iso": FR,
  "name": "France",
},
{
  "id": 3,
  "iso": GB,
  "name": "United Kingdom",
},
]

내 vue 컴포넌트:

<select v-model="country">
    <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>

ISO 코드를 기반으로 세 번째 json 인스턴스를 미리 선택하는 방법은 무엇입니까?

v-for 내부의 다음 코드가 작동하지 않음

:selected="country.iso === 'GB'"

물론 할 수 있다

data: function () {
    country: 3
}

단, id가 아닌 iso 코드에 따라 기본선택값을 선언하고 싶습니다.

iso를 모델 값으로 변경하고 싶지 않습니다.이것은 API에 포스트 리퀘스트로서 송신할 예정이기 때문입니다.이렇게 하면 json 객체 전체를 해석하여 ISO 코드에서 ID를 찾을 수 있지만 이것이 가장 깨끗한 솔루션이 될 수 있을지 모르겠습니다.

고마워요.

API 호출 후에 할 수 있습니다. 아마 당신은 그것을 가지고 있을 것입니다.mounted()그럼 필요한 것을 가치 있게 평가해 주세요.country가치.

다음과 같은 경우:

mounted() {
    axios.get('your-api-call-for-countries').then(response => {
         // Assign data from ...
         this.countries = response
         // Find Object which you want to be pre selected...
         let selected = this.countries.find(i => i.iso === 'GB')
         // Use id for your v-model...
         this.country = selected.id

         // or simplier
         this.country = this.countries.find(i => i.iso === 'GB').id
    })
}

그렇게 하려면 이 방법밖에 없는 것 같아요.id에 기반을 둔iso.

언급URL : https://stackoverflow.com/questions/66515463/vue-js-selected-option-not-based-on-value

반응형