父组件可以使用 props 把数据传给子组件
- 在父组件的 script 标签中使用 import 引入 子组件,并在 components 中注册
- 将子组件标签放在父组件的 template 里,并使用
v-bind:number = "n"
的方式动态绑定(v-bind可以简写为:) - 在子组件中定义
props:['number']
,并使用{{ number }}
,将父组件传送过来的数据展示在子组件中
代码示例
父组件
<template>
<div>
<p>父组件:{{ n }}</p>
<Son :number="n"></Son>
</div>
</template>
<script>
import Son from "@/components/Son";
export default {
data() {
return {
n: 0
}
},
components:{
Son
}
}
</script>
子组件
<template>
<div>
<p>子组件:{{ number }}</p>
</div>
</template>
<script>
export default {
props:['number']
}
</script>
子组件可以使用 $emit 触发父组件的自定义事件
- 在子组件中添加添加 methods,先在对应方法中写需要执行的操作,例如
this.count += 1;
- 在需要执行的操作写完后使用
this.$emit('numChange', this.count)
,将需要传送的数据 this.count 以 numChange 自定义事件传送至父组件 - 在父组件中,template 内子组件标签上添加绑定事件
v-on:numChange="getNewCount
,用于绑定父组件中接收处理子组件传送数据的方法,即子组件传来的数据需要经过getNewCount处理 - 在父组件data中定义
countFromSon:0
,用于接收子组件传回的值 - 在method中定义getNewCount函数,用于接收处理从子组件传回的值
- 最后可以通过
{{ countFromSon }}
将从子组件传回的值展示在父组件中
代码实例
父组件
<template>
<div>
<p>父组件:{{ countFromSon }}</p>
<Son @numChange="getNewCount"></Son>
</div>
</template>
<script>
import Son from "@/components/Son";
export default {
data() {
return {
countFromSon: 0
}
},
methods: {
getNewCount(val) {
this.countFromSon = val
}
},
components: {
Son
}
}
</script>
子组件
<template>
<div>
子组件:{{ count }}
<button @click="add">+1</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
add() {
this.count += 1;
this.$emit('numChange', this.count)
}
}
}
</script>