vue 父子组件双向绑定
vue组件有2大特性:
1.全局组件和局部组件
2.父子组件的数据传递
接下来直接用demo直接看如何传值(静态传值)
father.vue
<template> <div> <Counter num="10"></Counter>//静态传值 </div> </template> <script> import Counter from './child.vue' //引入子组件 export default { components:{Counter}, //命名子组件 data(){ } } </script>
child.vue
<template> <div> <button>+</button> <p><span>{{num}}</span></p> </div> </template> <script> export default { props:['num'], //props接收父组件传来的值。num必须和父组件的命名一样 methods:{ } } </script>
动态传值
father.vue
<template> <div> //动态改变num值需要用v-bind,子组件通$emit变量获取父组件的方法,接收事件名 <Counter v-bind:num="num" v-on:incre="increment" v-on:decre="decrement"></Counter> </div> </template> <script> import Counter from './child.vue' export default { components:{Counter}, data(){ return{ num:10, } }, methods:{ increment(){ this.num++; }, decrement(){ this.num--; } } } </script>
child.vue
<template> <div> <button @click="increment">+</button> <button @click="decrement">-</button> <p><span>{{num}}</span></p> </div> </template> <script> export default { data(){ return{} }, props:['num'], methods:{ increment(){ this.$emit('incre'); //获取父组件的方法,动态获取父组件的num值 }, decrement(){ this.$emit('decre'); } } } </script>
疾风知劲草,智者必怀仁