Vue官网链接-向子组件传递数据
Vue官网-Prop
父组件将值传递给子组件
父组件中的值可以通过v-bind与子组件中的props属性将值传递给子组件,也可以通过v-on与this.$emit()间接被子组件中的函数调用
1、使用v-bind将父组件中data中的键与子组件中的props键进行绑定
<body>
<div id="app">//props中的键与父组件里data中的键进行绑定在子组件里进行v-bind绑定从而达到父传子的效果, //数据的传递是实时的:当父组件中的数据变化是,子组件中的数据也会随之变化<hello v-bind:name="msg"></hello>
</div>
<script>var hello={props:{name: String,},template:'<h1>hello,{{name}}</h1>'}new Vue({el: '#app',data(){return{msg:'张三'}},components:{hello}})
</script>
</body>
2、通过ref与this.$refs父组件中的函数可以调用子组件中的函数,这种方式其实是子组件先调用父组件中定义的函数通过父组件中的函数改变父组件中的值,在由父组件通过v-bind传递给子组件,
<body>
<div id="app"><hello v-bind:name="msg" v-on:relation="change"></hello>
</div>
<template id="hel"><div><h1>{{name}}</h1><button v-on:click="$emit('relation')">Enlarge text</button></div>
</template><script>var hello={template:'#hel',props:{name:String}}new Vue({el: '#app',data(){return{msg:'张三'}},methods:{change(){this.msg='李四'}},components:{hello}})
</script>
</body>
子传父
Vue官网-$emit
Vue官网-.sync修饰符
通过.sync与this.$emit(‘update:props键名’,‘数据’)可以将子组件中的数据回传给父组件中的data键,类似于v-model的双向绑定
<body>
<div id="app">//使用.sync关键将子组件中的数据与父组件中的数据双向绑定<hello v-bind:name.sync="msg"></hello>
</div>
<template id="hel"><div><h1>{{name}}</h1><button v-on:click="changeMsg">Enlarge text</button></div>
</template><script>var hello={template:'#hel',props:{name:String},methods:{changeMsg(){this.$emit('update:name','赵六')}}}new Vue({el: '#app',data(){return{msg:'张三'}},components:{hello}})
</script>
</body>