programing

'createElement' 기능을 사용할 때 소품 바인딩을 반응적으로 만드는 방법

prostudy 2022. 7. 6. 22:01
반응형

'createElement' 기능을 사용할 때 소품 바인딩을 반응적으로 만드는 방법

Vue.config.devtools = false
Vue.config.productionTip = false
let modal = Vue.extend({
  template: `
<div class="modal">
  <p>Balance: {{ balance }}</p>
  <input @input="$emit('input', $event.target.value)" :value="value">
  <button @click="$emit('input', balance)">ALL</button>
</div>
`,
  props: ['balance', 'value']
})

function makeComponent(data) {
  return { render(h) { return h(modal, data) } }
}

Vue.component('app', {
  template: `
<div>
  <p>Balance: {{ balance }}</p>
  <p>To withdraw:  {{ withdrawAmount }}</p>
  <p>Will remain: {{ balance - withdrawAmount }}</p>
  <button @click="onClick">Withdraw</button>
  <modal-container ref="container"/>
</div>`,
  data () {
    return {
      withdrawAmount: 0,
      balance: 123
    }
  },
  methods: {
    onClick () {
      this.$refs.container.show(makeComponent({
        props: {
          balance: String(this.balance),
          value: String(this.withdrawAmount)
        },
        on: {
          input: (value) => {
            this.withdrawAmount = Number(value)
          }
        }
      }))
    }
  }
})

Vue.component('modal-container', {
  template: `
<div>
   <component v-if="canShow" :is="modal"/>
</div>
`,
  data () {
    return { modal: undefined, canShow: false }
  },
  methods: {
    show (modal) {
      this.modal = modal
      this.canShow = true
    },
    hide () {
      this.canShow = false
      this.modal = undefined
    }
  }
})


new Vue({
  el: '#app'
})
.modal {
  background-color: gray; 
  width: 300px; 
  height: 100px; 
  margin: 10px;
  padding: 10px;
}

* {
  font-family: "Source Sans Pro", "Helvetica Neue", Arial, sans-serif;
  color: #2c3e50;
  line-height: 25px;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
  <app></app>
</div>
This is a simplified version of our application using vue-modal의. The basic Idea is that we pass a component declaration along with required VNode Data(VNode Data) to the plugin function and it would append that component to a pre-defined DOM point with proper data bindings.

그리고 우리의 활용 사례는 다음과 같습니다.

  1. 사용자가 'Withdraw
  2. 모달에 사용자의 밸런스를 표시하는 입력 필드 및 정적 필드가 팝업 표시됨
  3. 사용자가 인출하고 싶은 금액을 입력하면 해당 금액과 결과 잔액이 착신자 구성요소에 표시됩니다.

입력란 옆에 'ALL' 버튼이 있어 잔액과 동일한 숫자를 쉽게 입력할 수 있습니다.

문제:사용자가 'ALL'을 클릭하면 '모달' 구성 요소가 잔액 값과 함께 '입력' 이벤트를 발생시키고 착신자 구성 요소가 해당 이벤트를 수신하여 'drawAmount'를 업데이트합니다.그러나 'drawAmount'는 '가치' 소품으로서 '모달'로 돌아가 입력 필드를 업데이트해야 하는데, 이는 발생하지 않습니다.

언급URL : https://stackoverflow.com/questions/51321909/how-to-make-the-props-binding-reactive-when-using-createelement-function

반응형