1.父组件
<template>
<div>
我是父组件
<Son :son="son" @sonClick="sonClick"></Son> <!-- 我是子组件 -->
</div>
</template>
<script>
import { defineComponent} from 'vue'
import Son from './son.vue' //这里是在同级目录 引用组件
export default defineComponent({
name: 'father',
components: { Son }, //注册组件
setup(){
const state = reactive({
son:{name:'儿子',age:12},
})
const sonClick = data =>{ //子组件调用的函数
console.log(data) //结果为 你好
}
return {
...toRefs(state),
sonClick,
}
}
)}
</script>
2.子组件
<template>
<div>
我是子组件
{{info.name}} <!--儿子-->
{{info.age}} <!--12-->
<button @click="sonClick('你好')">调用父组件事件</button>
</div>
</template>
<script>
import { defineComponent} from 'vue'
export default defineComponent({
name: 'son',
props:[son], //接受父组件传过来的值
emits:['sonClick'],//传给父组件的事件
setup(data,{emit}){ //data里面放的就是接受到的所有父组件传过来的参数,
//emit向父组件传递事件
const state = reactive({
info:data.son, //接收到父组件传过来的值
})
const sonClick = data => {
console.log('我是子组件我要调用父组件事件')
emit('sonClick',data) //第一个是事件,data为传递的参数
}
return {
...toRefs(state),
sonClick,
}
}
)}
</script>
1.使用子组件
1.引入想要使用的子组件
import son from './son.vue'
2.注册组件
components: { Son },
3.把组件放到合适的位置
<div>
我是父组件
<Son></Son> <!-- 我是子组件 -->
</div>
2.父组件给子组件传值
1.在子组件的标签上绑定值
<Son :son="son"></Son>
2.接受父组件传过来的值
props:[son],
const state = reactive({
info:data.son, //接收到父组件传过来的值
})
3.子组件调用父组件事件
1.子组件创建点击事件,emit传递给父组件事件
<button @click="sonClick('你好')">调用父组件事件</button>
const sonClick = data => {
console.log('我是子组件我要调用父组件事件')
emit('sonClick',data) //第一个是事件,data为传递的参数
}
2.父组件的son标签绑定传递过来的事件,触发事件
<Son @sonClick="sonClick"></Son>
const sonClick = data =>{ //子组件调用的函数
console.log(data) //结果为 你好
}
只是一个很简单的引用、传递和调用。