父向子传值
1.父组件通过v-bind:属性绑定的形式,把数据传递给子组件
<counter :number="count"></counter>
2.子组件通过props接收父组件传递过来的数据
<div>子组件的值~~{{number}}</div>
export default {
name: 'Counter',
props:['number'],
}
子向父传值
1.在v-bind:指令之前添加v-model指令
<counter v-model:number="count"></counter>
2.在子组件中声明emits自定义事件,格式为update:xxx
export default {
name: 'Counter',
props:['number'],
emits:['update:number'],
}
3.调用$emit()触发自定义事件,更新父组件中的数据
add(){
this.$emit('update:number',this.number + 1);
}
完整代码:
<template> <div>父组件count的值~~{{count}}</div> <button type="button" @click="count+=1">+1</button> <hr/> <counter v-model:number="count"></counter> </template> <script> import Counter from './components/Counter.vue' export default { components:{ Counter }, data(){ return{ count:0 } }, methods:{ } } </script> <style lang="less" scoped></style>
<template> <div> <div>子组件的值~~{{number}}</div> <button @click="add">+1</button> </div> </template> <script> export default { name: 'Counter', props:['number'], emits:['update:number'], data() { return { } }, methods:{ add(){ this.$emit('update:number',this.number + 1); } } } </script> <style scoped lang="less"> </style>
记录日常心得体会~~