使用'createElement'函数时如何使道具绑定具有反应性

时间:2018-07-13 09:26:07

标签: vue.js vuejs2 vue-reactivity

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>
这是使用vue-js-modal的应用程序的简化版本。基本思想是,我们将组件声明以及必需的VNodeData传递给插件函数,并将该组件附加到具有适当数据绑定的预定义DOM点上。

我们的用例是:

  1. 用户点击“提款”
  2. 弹出一个带有输入字段和静态字段的模块,显示用户的余额
  3. 用户输入他/她要提取的金额,并且该金额和产生的余额显示在被叫方组件中。

输入字段旁边有一个“全部”按钮,用户可以轻松输入等于其余额的数字

问题:当用户单击“全部”时,“模式”组件将触发一个带有余额值的“输入”事件,被调用者组件将收到该事件并更新其“ withdrawAmount”。但是应该将“ withdrawAmount”作为“值”属性传递回“模式”,并进一步更新输入字段,这不会发生。

0 个答案:

没有答案