IT이야기

계산된 특성에 대한 동적 "v-model" - 경로 파라미터를 기반으로 함

cyworld 2022. 3. 18. 21:45
반응형

계산된 특성에 대한 동적 "v-model" - 경로 파라미터를 기반으로 함

나는 루트에 전달된 이름에 따라 다양한 vuex 속성을 설정하는 데 사용할 수 있는 구성 요소를 만들고 있어.이것의 순진한 요지는 다음과 같다.

<template>
  <div>
    <input v-model="this[$route.params.name]"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  }
}
</script>

내가 합격했다는 것을 주의하라.this[$route.params.name]에게v-model역동적으로 만들기 위해서.이는 설정(구성 요소 로드 양호)에 사용되지만 값을 설정하려고 할 때 다음과 같은 오류가 표시됨:

Cannot set reactive property on undefined, null, or primitive value: null

내 생각에 이것은 때문이다.this안쪽에v-model정의가 없어지다(?)

어떻게 하면 이 일을 해낼 수 있을까?

갱신하다

나는 또한 왜 이것이 작동하지 않는지 궁금할 것이다(컴파일 오류:

<template>
  <div>
    <input v-model="getComputed()"/>
  </div>
</template>

<script>
export default {
  computed: {
    foo: {
      get(){ return this.$store.state.foo; },
      set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
    },
    bar: {
      get(){ return this.$store.state.bar; },
      set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
    },
  },
  methods: {
    getComputed(){
      return this[this.$route.params.name]
    }
  }
}
</script>

네 안에 있는 모든 것<template>에 있다this범위, 그러니까this정의되지 않았다.

v-model에 대한 통사설탕일 뿐이다.:value그리고@input에 대한 사용자 정의 이벤트와 계산된 속성으로 이 문제를 처리할 수 있다.:value.

계산된 속성을 getter와 setter와 함께 사용할 수도 있다.

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      this.$store.commit('updateValue', { name: this.$route.params.name, value})
    }
  }
}

편집 세터 내에서 더 많은 논리를 수행할 수 있는 경우 그렇게 분리하고 단순성을 유지하면서 하나의 계산된 속성에 충실할 것이다.

computed: {
  model: {
    get: function () {
      return this.$store.state[this.$route.params.name]
    },
    set: function (value) {
      switch(this.$route.params.name) {
        case 'foo':
          return this.foo(value)
        default:
          return this.bar(value)
      }
    }
  }
},
methods: {
  foo(val) {
    this.$store.commit(...)
  },
  bar(val) {
    this.$store.commit(...)
  }
}

참조URL: https://stackoverflow.com/questions/54198300/dynamic-v-model-for-computed-properties-based-on-route-param

반응형