vue2.0实现父子组件数据双向绑定
2017-09-14 11:02
821 查看
vue2.0父子组件间数据只能实现单向绑定,就是如果子组件修改了父组件传过来的data值,就会报错,
但是如果我们有这种双向绑定的需求,就要通过this.$emit暴露一个方法出去,然后由父组件决定是否调用。
【父】:
【子】:
但是如果我们有这种双向绑定的需求,就要通过this.$emit暴露一个方法出去,然后由父组件决定是否调用。
【父】:
<template> <div id="app"> 父:{{ count }} <button @click="add">+</button> <button @click="minus">-</button> <hello @syncCount="changeCount" :count="count"></hello> </div> </template> <script> import Hello from './components/Hello' export default { data() { return { count: 1 } }, components: { Hello }, methods: { add() { this.count++; }, minus() { this.count--; }, changeCount(val){ this.count = val; } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
【子】:
<template> <div class="hello"> 子:{{ countClone }} <button @click="add">+</button> <button @click="minus">-</button> </div> </template> <script> export default { props: { count: { type: Number } }, data() { return { countClone: this.count } }, watch: { count(val) { this.countClone = val; }, countClone(val){ this.$emit('syncCount',val); } }, methods: { add() { this.countClone++; }, minus() { this.countClone--; } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
相关文章推荐
- Vue2.0实现组件数据的双向绑定问题
- Vue 2.0学习笔记:实现组件数据的双向绑定
- Vue父子组件双向绑定传值的实现方法
- vue父子组件传值,实现深度监听对象,双向绑定
- Angular:实现组件间双向数据绑定
- vue2.X props 数据传递 实现组件内数据与组件外的数据的双向绑定
- Angular自定义组件实现数据双向数据绑定的实例
- vue父组件和子组件通过sync实现双向数据绑定
- 【VUE】.NET实现Tree组件双向绑定数据(1)
- 【VUE】.NET实现Tree组件双向绑定数据(2)
- Angular 5 子组件与父组件实现数据双向绑定
- 【VUE】.NET实现Tree组件双向绑定数据(3)-资源分配
- Vue数据双向绑定原理及简单实现方法
- vue 自定义组件 v-model双向绑定、 父子组件同步通信
- vue实现数据双向绑定原理剖析
- angular学习总结九——父组件与子组件数据的双向绑定
- 自定义Angular指令与jQuery实现的Bootstrap风格数据双向绑定的单选&多选下拉框
- react.js 父子组件数据绑定实时通讯
- Vue4种父子组件数据双向传递
- AngularJS的数据双向绑定是怎么实现的?