Vue+ts 如何实现父组件和子组件通信
父组件向子组件通信
首先,写一个子组件,名字叫sonComponent。
<template><div class="son" ><span>子组件{{ count }}</span></div>
</template>
<script setup lang="ts">
import { DefineProps} from 'vue';
const props = defineProps({count:{type:Number,default:20,},})
</script>
<style scoped>
.son{background:red;width:50%;height: 60%;text-align: center;span{display: inline-block;margin-top: 20px;}
}
</style>
代码解析:
1.这里子组件里面放了一个文本内容(span),<span>
里面放了响应变量count,这个响应变量是子组件从父组件获得的。
2.父组件向子组件通信需要我们使用vue库里面的DefineProps
,定义哪些变量是需要从父组件获取的,这时把count放到DefineProps
中。
3.在定义count的时候,这里用了typescript的语言格式,type表明count的类型是整数型,default表示默认值为20。
然后写一个父组件,如下所示
<template><div class="grandfather"><div class="father" @click="Click"><h1>父组件</h1><sonComponent :count="val"/></div></div>
</template><script setup lang="ts">
import sonComponent from "@/components/son_component/sonComponent.vue";
import {ref} from 'vue'
let val = ref<Number>(20);
const Click=()=>{val.value ++;
}
</script><style scoped lang="scss">
.grandfather{width:100%;height: 300px;display: flex;justify-content: center;align-items: center;margin-top:200px;.father{border: 1px solid red;width:400px;height: 200px;text-align: center;display: flex;flex-direction: column;justify-content: center;align-items: center;}
}
</style>
代码解析:
1.父组件中内嵌了子组件,点击父组件就会让子组件的count变量加一。
2.用@click
绑定点击事件,这里绑定了Click()
事件,该事件让响应变量val加一。
3.将响应变量val传到子组件中,用v-model绑定机制将子组件的count和响应变量val绑定在一起。
这时就成功地实现了父组件向子组件通信的过程。
1. 默认情况下如下图所示
2. 点击父组件之后会让子组件接收到父组件传过来的count信息改变子组件的显示内容。
子组件向父组件通信
子组件的代码:
<template><div class="son" @click="Click"><span>子组件{{ count }}</span></div>
</template><script setup lang="ts">import { DefineProps ,defineEmits} from 'vue';
const props = defineProps({count:{type:Number,default:20,},})
const emit = defineEmits(['sendMessage'])const Click = ()=>{emit('sendMessage','子节点被点击')
}</script><style scoped>
.son{background:red;width:50%;height: 60%;text-align: center;span{display: inline-block;margin-top: 20px;}
}
</style>
代码解析:
- 首先引入vue库的
DefineEmits
函数,在DefinEmits
中定义emit事件的名字,比如说我在这里定义了sendMessage。 - 写一个点击事件,绑定Click函数,如果被点击,向父组件发送消息“子组件已被点击”。
父组件代码:
<template><div class="grandfather" ><div class="father" @click="Click"><h1>父组件</h1><sonComponent :count="val" @sendMessage="getMessage"/>{{ message }}</div></div>
</template><script setup lang="ts">
import sonComponent from "@/components/son_component/sonComponent.vue";
import {ref} from 'vue'
let message = ref<string>('要接受的子组件的信息');
let val = ref<Number>(20);
const Click=()=>{val.value ++;
}const getMessage = (msg)=>{message.value= msg as string
}
</script><style scoped lang="scss">
.grandfather{width:100%;height: 300px;display: flex;justify-content: center;align-items: center;margin-top:200px;.father{border: 1px solid red;width:400px;height: 200px;text-align: center;display: flex;flex-direction: column;justify-content: center;align-items: center;}
}
</style>
代码解析:
父组件绑定了@sendMessage方法去获取子组件发过来的信息,绑定getMessage方法,用msg接受子组件传过来的信息。然后在父组件中显示。
-
没有点子组件前如下
-
点了子组件后
-