vue实现双向绑定的方法:1、利用v-model指令实现绑定,自定义组件上的v-model相当于传递了modelvalue prop并接收抛出的update:modelvalue事件;2、利用vue-better-sync插件实现绑定;3、利用v-bind.sync修饰符,语法“473ae2310c449e2f362f57c40bea2951”。
本教程操作环境:windows7系统、vue3版,dell g3电脑。
vue 实现双向绑定的几种方法1、v-model 指令a5c499a874abfc2f90cd210a938c74257881aca7d6349344d239a074a7a8dcff4749ad9934054ab2b11f0f2ad931d449
如果要将属性或事件名称更改为其他名称,则需要在 childcomponent 组件中添加 model 选项:
<!-- parentcomponent.vue --><childcomponent v-model="pagetitle" />
// childcomponent.vueexport default { model: { prop: 'title', event: 'change' }, props: { // 这将允许 `value` 属性用于其他用途 value: string, // 使用 `title` 代替 `value` 作为 model 的 prop title: { type: string, default: 'default title' } }}
所以,在这个例子中 v-model 是以下的简写:
<childcomponent :title="pagetitle" @change="pagetitle = $event" />
在 vue 3.x 中,自定义组件上的 v-model 相当于传递了 modelvalue prop 并接收抛出的 update:modelvalue 事件:
<childcomponent v-model="pagetitle" /><!-- 是以下的简写: --><childcomponent :modelvalue="pagetitle" @update:modelvalue="pagetitle = $event"/>
vue3 可以绑定多个v-model, 例如:<childcomponent v-model:title="pagetitle" v-model:name="pagename" />
2、vue-better-sync 插件有需求如此:开发一个 prompt 组件,要求同步用户的输入,点击按钮可关闭弹窗。
一般我们会这样做:
<template> <div v-show="_visible"> <div>完善个人信息</div> <div> <div>尊姓大名?</div> <input v-model="_answer" /> </div> <div> <button @click="_visible = !_visible">确认</button> <button @click="_visible = !_visible">取消</button> </div> </div></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>
写一两个组件还好,组件规模一旦扩大,写双向绑定真能写出毛病来。于是,为了解放生产力,有了 vue-better-sync 这个轮子,且看用它如何改造我们的 prompt 组件:
<template> <div v-show="actualvisible"> <div>完善个人信息</div> <div> <div>尊姓大名?</div> <input v-model="actualanswer" /> </div> <div> <button @click="syncvisible(!actualvisible)">确认</button> <button @click="syncvisible(!actualvisible)">取消</button> </div> </div></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>
vue-better-sync 统一了 v-model 和 .sync 传递数据的方式,你只需 this.actual${propname} = newvalue 或者 this.sync${propname}(newvalue) 即可将新数据传递给父组件。
github:fjc0k/vue-better-sync
3、使用 v-bind.sync修饰符在某些情况下,我们可能需要对某一个 prop 进行“双向绑定”(除了前面用 v-model 绑定 prop 的情况)。为此,我们建议使用 update:mypropname 抛出事件。例如,对于在上一个示例中带有 title prop 的 childcomponent,我们可以通过下面的方式将分配新 value 的意图传达给父级:
this.$emit('update:title', newvalue)
如果需要的话,父级可以监听该事件并更新本地 data property。例如:
<childcomponent :title="pagetitle" @update:title="pagetitle = $event" />
为了方便起见,我们可以使用 .sync 修饰符来缩写,如下所示:
<childcomponent :title.sync="pagetitle" />
vue3 移除.sync
【相关推荐:vuejs视频教程、web前端开发】
以上就是vue实现双向绑定有哪几个方法的详细内容。