江西学校网站建设,湖南网站seo推广,做网站用的编程语言,wordpress 推广提成uniapp 微信小程序#xff1a;v-model双向绑定问题#xff08;自定义 props 名无效#xff09; 前言问题双向绑定示例使用 v-model使用 v-bind v-on使用 sync 修饰符 参考资料 前言
VUE中父子组件传递数据的基本套路#xff1a;
父传子 props子传父 this.$emit(事件名, … uniapp 微信小程序v-model双向绑定问题自定义 props 名无效 前言问题双向绑定示例使用 v-model使用 v-bind v-on使用 sync 修饰符 参考资料 前言
VUE中父子组件传递数据的基本套路
父传子 props子传父 this.$emit(事件名, 数据);使用 sync 修饰符实现支持同步数据
问题 因为用的是 uniapp 开发小程序所以要考虑到兼容性问题不要把自己当正经VUE2。 小程序虽然支持 v-model 指令但不支持 model 选项。 所以要么子组件中声明默认的 value 这个 props 来接收值。 要么手动绑定属性和事件
双向绑定示例
使用 v-model
由于小程序不支持 model 选项。 这个方案中子组件里只能使用 value 接收数据更新时触发 input。
父组件
templateviewviewtext父组件{{ msg }}/text/viewvmodel-component v-modelmsg/vmodel-component/view
/templatescriptexport default {data() {return { msg: 大家好我是使用 v-model }},methods: {}}
/scriptstyle
/style子组件
templateview view 子组件{{value}} /viewbutton clickonclick 更新/button/view
/templatescriptexport default {data() {return {};},props:{value:{ type: String, default: 未收到父值 }},methods:{onclick(e){this.$emit(input, 我是笨笨); // v-mode }}}
/scriptstyle
/style使用 v-bind v-on
当然一般都会用简写形式 v-bind:缩写为 : v-on:缩写为
由于是自己手绑定props 和 事件名都可以自己定。 比如在子组件中我就用 msg 接收数据。 事件我自己取名叫 customEvent。
templateviewviewtext父组件{{ msg }}/text/viewnovmodel-component :msgmsg customEvente msg e/novmodel-component!-- novmodel-component :msgmsg input msg $event /novmodel-component --/view
/templatescriptexport default {data() {return { msg: 大家好我是不使用 v-model }},methods: {}}
/scriptstyle
/style子组件
templateview view 子组件{{msg}} /viewbutton clickthis.$emit(customEvent, 我是笨笨) 更新/button/view
/templatescriptexport default {data() {return {};},props:{msg:{ type: String, default: 未收到父值 }},methods:{}}
/scriptstyle
/style使用 sync 修饰符
使用 sync 时可以自己决定绑到子组件的哪个 props 上比如就绑到了 msg 上。 同步数据时触发 update:要更新的props
父组件
templateviewviewtext父组件{{ msg }}/text/viewsync-component :msg.syncmsg/sync-component/view
/templatescriptexport default {data() {return { msg: 大家好我是使用 sync 修饰符实现同步数据 }},methods: {}}
/scriptstyle
/style子组件
templateview view 子组件{{msg}} /viewbutton click$emit(update:msg, 我是笨笨) 更新/button/view
/templatescriptexport default {data() {return {};},props: {msg: { type: String, default: 未收到父值 }},methods:{}}
/scriptstyle
/style参考资料
uniapp官方文档 模板指令 v-model uniapp官方文档 .sync 修饰符
vue2官方文档选项 model