一、 父传子
父传子十分好理解,需要先创建一个子,一个父如图所示。
1.1 步骤图解
App.vue中步骤如下:
- 导入子组件
- 声明子组件
- 在Html中使用子组件并添加 :msg=“msg”
这时由steup返回的msg就会被子组件接收
child.vue中步骤如下
- 接收msg
- 展示msg
这时就可以正常展示msg了如图
1.2 App.vue完整代码:
<template>
<div>
<h1>父</h1>
<h3>{{msg}}</h3>
<hr>
<Child :msg="msg"/>
</div>
</template>
<script>
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";
export default defineComponent({
components: {
Child,
},
name: "App",
setup() {
const msg = ref("小天英俊潇洒")
return{
msg,
}
},
});
</script>
<style scoped>
</style>
1.3 child.vue完整代码:
<template>
<div>
<h1>子</h1>
<h3>{{msg}}</h3>
</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name:'Child',
props:["msg"],
setup(props,context){
return{
}
}
})
</script>
<style scoped>
</style>
二、子传父
2.1 步骤图解
App.vue步骤:
- 自定义回调函数
- 编写回调函数
- 返回回调函数
child.vue步骤:
- 编写按钮分发事件
- 编写按钮触发函数,使用emit传递数据
- 返回按钮触发函数
ok子传父搞定
2.2 App.vue完整代码
<template>
<div>
<h1>父</h1>
<h3>{{ msg }}</h3>
<hr />
<Child :msg="msg" @zcf="zcf" />
</div>
</template>
<script>
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";
export default defineComponent({
components: {
Child,
},
name: "App",
setup() {
const msg = ref("小天英俊潇洒");
// 回调函数
const zcf = (text) => {
msg.value += text;
};
return {
msg,
zcf,
};
},
});
</script>
<style scoped>
</style>
2.3 child.vue完整代码
<template>
<div>
<h1>子</h1>
<h3>{{msg}}</h3>
<button @click="emit_zcf">子传父</button>
</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name:'Child',
props:["msg"],
setup(props,context){
// 按钮触发函数
const emit_zcf = () => {
context.emit('zcf','子传父')
}
return{
emit_zcf
}
}
})
</script>
<style scoped>
</style>