這篇文章主要介紹了Vue 實現雙向綁定的四種方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
<input v-model="text" />
上例不過是語法糖,展開來是:
<input :value="text" @input="e => text = e.target.value" />
##
<my-dialog :visible.sync="dialogVisible" />
<my-dialog :visible="dialogVisible" @update:visible="newVisible => dialogVisible = newVisible" />
this.$ emit('update:visible', newVisible) 即可。
{ render(h) { return h('my-dialog', { props: { value: this.dialogVisible }, on: { input: newVisible => this.dialogVisible = newVisible } }) } }
#
{ render(h) { return h('my-dialog', { props: { visible: this.dialogVisible }, on: { change: newVisible => this.dialogVisible = newVisible } }) } }
{ render(h) { return h('my-dialog', { model: { value: this.dialogVisible, callback: newVisible => this.dialogVisible = newVisible } }) } }
{ render() { return ( <my-dialog {...{ model: { value: this.dialogVisible, callback: newVisible => this.dialogVisible = newVisible } }} /> ) } }
<template> <p v-show="_visible"> <p>完善个人信息</p> <p> <p>尊姓大名?</p> <input v-model="_answer" /> </p> <p> <button @click="_visible = !_visible">确认</button> <button @click="_visible = !_visible">取消</button> </p> </p> </template> <script> export default { name: 'prompt', props: { answer: String, visible: Boolean }, computed: { _answer: { get() { return this.answer }, set(value) { this.$emit('input', value) } }, _visible: { get() { return this.visible }, set(value) { this.$emit('update:visible', value) } } } } </script>
<template> <p v-show="actualVisible"> <p>完善个人信息</p> <p> <p>尊姓大名?</p> <input v-model="actualAnswer" /> </p> <p> <button @click="syncVisible(!actualVisible)">确认</button> <button @click="syncVisible(!actualVisible)">取消</button> </p> </p> </template> <script> import VueBetterSync from 'vue-better-sync' export default { name: 'prompt', mixins: [ VueBetterSync({ prop: 'answer', // 设置 v-model 的 prop event: 'input' // 设置 v-model 的 event }) ], props: { answer: String, visible: { type: Boolean, sync: true // visible 属性可用 .sync 双向绑定 } } } </script>
this.actual${PropName} = newValue 或
this.sync${PropName}(newValue) 即可將新資料傳遞給父組件。
#
以上是Vue 實作雙向綁定的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!