programing

v-model 값이 변경될 때 사용자 지정 Vue 선택 구성 요소가 선택한 옵션을 업데이트하지 않음

prostudy 2022. 8. 22. 21:29
반응형

v-model 값이 변경될 때 사용자 지정 Vue 선택 구성 요소가 선택한 옵션을 업데이트하지 않음

Vue 커스텀 컴포넌트로 선택 항목을 랩하려고 합니다.v-model도큐먼트에 기재되어 있는 패턴입니다.

커스텀 셀렉트컴포넌트에 대해서, 다음의 에러 메세지가 표시됩니다.

[Vue warn] :상위 구성 요소가 다시 렌더링될 때마다 값이 덮어쓰기되므로 프로포트를 직접 변환하지 마십시오.대신 프로펠러 값을 기반으로 데이터 또는 계산된 속성을 사용하십시오.변형되는 프로펠러: "가치"

에서 발견되다.

--->

하지만 제가 만들 때value데이터 속성, 기대했던 기능을 해방합니다.즉, 바인딩된 값이 변경되면 선택 상자가 업데이트되지 않습니다.양방향 바인딩이 손실되었습니다.

경고 없이 예상되는 동작을 유지하는 올바른 방법은 무엇입니까?

다음은 문제를 보여주는 대화형 예입니다(전체 화면에서 가장 잘 볼 수 있음).

Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
  methods: {
    changed() {
      // custom input components need to emit the input event
      this.$emit('input', event.target.value)
    },
  },
})

Vue.component('dynamic-select-ex2', {
  template: '#dynamic-select-template',
  props: ['options'],
  data() {
    return {
      value: null,
    }
  },
  methods: {
    changed() {
      // custom input components need to emit the input event
      this.$emit('input', event.target.value)
    },
  },
})

let example = new Vue({
  el: '#example',
  data() {
    return {
      selected: null,
      options: [
        { text: 'Hello', value: 1 },
        { text: 'World', value: 2 },
        { text: 'Blah', value: 3 },
        { text: 'Blerg', value: 4 },
      ]
    }
  },
  computed: {
   text() {
     if (!this.selected) return
     return this.options.find(({ value }) => value == this.selected).text
   },
  },
  methods: {
    select(value) {
      this.selected = value
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="dynamic-select-template">
  <select v-model="value" @change="changed">
    <option v-for="option in options" :value="option.value">{{ option.text }}</option>
  </select>
</script>

<div id="example">
  <label for="direct">Vue behaviour for native select</label><br>
  <select id="direct" v-model="selected">
    <option v-for="option in options" :value="option.value">{{ option.text }}</option>
  </select><br>

  <div>Vue behaviour for custom component. `value` is a prop. Warning output in console when user selects option</div>
  <dynamic-select-ex1 v-model="selected" :options="options"></dynamic-select-ex1><br>

  <div>Vue behaviour for custom component. `value` is a data property. two-way binding is broken.  Selected option not updated when `value` changes.</div>
  <dynamic-select-ex2 v-model="selected" :options="options"></dynamic-select-ex2><br>
  
  <br>Selected: {{ text }}<br><br>
  
  <button @click="select(1)">Hello</button>
  <button @click="select(2)">World</button>
  <button @click="select(3)">Blah</button>
  <button @click="select(4)">Blerg</button><br>

</div>

계산 세터

위해서v-model, 계산 세터를 사용합니다.v-model대신value프로펠러의 변형을 피하기 위해서입니다.이 모든 것을 없앨 수 있습니다.change청취자

<select v-model="model">
  <option v-for="option in options" :value="option.value">{{ option.text }}</option>
</select>
Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
  computed: {
    model: {
      get() { return this.value },
      set(value) { this.$emit('input', value) }
    }
  }
})

계산된 값에 액세스하면 프로펠러 값이 반환되고 설정되면 대신 방출됩니다.

또는:value,@input,그리고.$event.target.value

또 다른 옵션은 1방향 바인딩을 하는 것입니다.value그리고.$emit템플릿에서:

<select :value="value" @input="$emit('input', $event.target.value)">
  <option v-for="option in options" :value="option.value">{{ option.text }}</option>
</select>
Vue.component('dynamic-select-ex1', {
  template: '#dynamic-select-template',
  props: ['value', 'options'],
})

언급URL : https://stackoverflow.com/questions/66558889/custom-vue-select-component-not-updating-selected-option-when-v-model-value-chan

반응형