source

Vuex v-model을 개체 상태 필드로

factcode 2022. 8. 21. 14:05
반응형

Vuex v-model을 개체 상태 필드로

다음과 같은 Vuex 상태가 있습니다(게터라는 이름의 것도 있습니다).configs:

configs: {

    1303401: {

        exampleValue: 'test'

    }

}

또한 v-model을 사용하여exampleValueVuex 스토어 상태:

<input type="text" v-model="config.exampleValue" />

다음은 다음 중 하나를 반환하기 위해 사용하는 계산 속성은 다음과 같습니다.config:

config: {

    get () {

        return this.$store.getters.configs[1303401]

    },
    set (value) {

        //this should set the configs[1303401] field with the updated exampleValue
        this.$store.dispatch('UPDATE_CONFIG', value)

    }


}

입력 값이 다음 값으로 변경됩니다.config.exampleValue따라서 계산된 데이터는 정의되지 않지만 Vuex 상태는 업데이트되지 않습니다.

그리고 내가 노력한다면console.logsetter의 값은 콘솔에 아무것도 표시되지 않으므로 setter는 실행조차 되지 않습니다.

이것은 아마도 그것이 세팅이 되지 않기 때문일 것이다.config계산된 속성, 단,config.exampleValue하지만 어떻게 대처해야 할지 모르겠어요

상기 @asi-ple에서 설명한 바와 같이 반품 방법 변경configs[1303401].exampleValue동작합니다만, 문제는 설정에 필드가 더 많고 페이지에 입력이 더 많다는 것입니다.이 방법으로 모든 필드에 대해 계산 속성을 작성해야 합니다.

실제로 필드가 여러 개일 경우 여기서 논리를 세울 수 있습니다.

예를 들어 다음과 같은 경우

configs: {
    1303401: {
        exampleValue: 'test',
        exampleValue2: 'test2',
        exampleValue3: 'test3',
        ...
    } 
}

템플릿을 다음으로 변경해야 합니다.

<input type="text" :value="config[1303401].exampleValue1" @input="update_config($event, 'exampleValue1')" />
<input type="text" :value="config[1303401].exampleValue2" @input="update_config($event, 'exampleValue2')" />
<input type="text" :value="config[1303401].exampleValue3" @input="update_config($event, 'exampleValue3')" />

그리고 당신의 이런 방법들은

methods:{
    update_config($event, where){
          this.$store.commit("UPDATE_CONFIG", {value: $event.target.data, where: where})
    }
}

그러면 당신의 돌연변이 처리기가

UPDATE_CONFIG(state, payload){
       state.configs[1303401][payload.where] = payload.value
}

기본적으로 위의 코드에서는 템플릿에서 양방향 데이터 바인딩을 사용해야 하는 상태에서 설정 데이터를 만듭니다.그런 다음 입력을 작성합니다.value working like get methods, @input listener는 set methods, update_config는 변경을 커밋하고 올바른 위치에 변환 핸들러를 설정합니다.

get 객체의 속성을 가진 v-model을 사용하고 있고 setter가 작업을 하지 않기 때문인 것 같습니다.속성으로만 작업할 수 있습니다. 계산된 속성은 다음과 같습니다.

config: {
    get () {
        return this.$store.getters.configs[1303401].exampleValue
    },
    set (value) {
        this.$store.dispatch('UPDATE_CONFIG', value)
    }
}

및 템플릿:

<input type="text" v-model="config" />

따라서 스토어 액션에서 새로운 exampleValue 값을 얻을 수 있습니다.또한 계산된 속성(폼 포함)에서 getter/setter에 개체를 사용하지 않도록 하십시오. 숨겨진 트랩이 많이 있습니다.

언급URL : https://stackoverflow.com/questions/61979328/vuex-v-model-to-an-object-state-field

반응형