主要会讲以下几种常用的组件通信方式
- props
- emit
- ref
- pinia
1.父传子(props)
在子组件上自定义一个属性,属性名随意,属性值是你要传递的参数。
效果
父组件
<template>
<childVue :title="message"></childVue>
</template>
<script setup lang="ts">
import childVue from '@/components/child.vue';
const message='父子传参'
</script>
<style scoped>
</style>
子组件
<template>
<div>
{{ title }}
</div>
</template>
<script setup lang="ts">
const props=defineProps({
title:{
type:String,
default:''
}
})
console.log(props.title);
</script>
2.子传父(emits)
**
**
父组件
<template>
<div>{{ message }}</div>
<childVue @msg="changMessage"></childVue>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import childVue from '@/components/child.vue';
let message=ref('布丁')
//更改message的值,data是从子组件传过来的
function changMessage(data:any){
message.value=data
}
</script>
子组件
<template>
<div>
子组件:<button @click="handClick">子组件按钮</button>
</div>
</template>
<script setup lang="ts">
const emit=defineEmits(['msg'])
function handClick(){
//参数1:事件名
//参数2:传给父组件的值
emit('msg','奶酪')
}
</script>
3.父组件直接获取子组件(v-model)
效果
父组件
<template>
<div>
<childVue ref="childRef"></childVue>
<button @click="btn">点击</button>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import childVue from '@/components/child.vue';
const childRef=ref()
const btn=()=>{
console.log(childRef.value.arr);
}
</script>
子组件
<template>
<div>
子组件
</div>
</template>
<script setup lang="ts">
import {ref,defineExpose} from 'vue'
const arr=ref('暴露出来的')
defineExpose({arr})
</script>
4.pinia
效果
在 store 里创建 index.js 和 user.js
index.js
import { createPinia } from 'pinia'
const store = createPinia()
export default store
user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user',{
state: () => {
return {
name: '雷猴'
}
},
getters: {
fullName: (state) => {
return '我叫 ' + state.name
}
},
actions: {
updateName(name) {
this.name = name
}
}
})
然后在 src/main.ts中引入 stores
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import store from '@/stores'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(store)
app.mount('#app')
在组件中使用
<template>
<div>
<div>name: {{ name }}</div>
<div>全名:{{ fullName }}</div>
<button @click="handleClick">修改</button>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
// 建议
const { name, fullName } = storeToRefs(userStore)
function handleClick() {
userStore.updateName('李四')
}
</script>