Vue2.x組件通信12種方式寫在後面了,先來 Vue3 的
奧力給!
Vue3 組件通信方式Vue3 通信使用寫法1. props用 props 傳數據給子組件有兩種方法,如下
方法一,混合寫法
// Parent.vue 傳送
<child :msg1="msg1" :msg2="msg2"></child>
<script>
import child from "./child.vue"
import { ref, reactive } from "vue"
export default {
data(){
return {
msg1:"這是傳級子組件的信息1"
}
},
setup(){
// 創建一個響應式數據
// 寫法一 適用於基礎類型 ref 還有其他用處,下面章節有介紹
const msg2 = ref("這是傳級子組件的信息2")
// 寫法二 適用於複雜類型,如數組、對象
const msg2 = reactive(["這是傳級子組件的信息2"])
return {
msg2
}
}
}
</script>
// Child.vue 接收
<script>
export default {
props: ["msg1", "msg2"],// 如果這行不寫,下面就接收不到
setup(props) {
console.log(props) // { msg1:"這是傳給子組件的信息1", msg2:"這是傳給子組件的信息2" }
},
}
</script>方法二,純 Vue3 寫法
// Parent.vue 傳送
<child :msg2="msg2"></child>
<script setup>
import child from "./child.vue"
import { ref, reactive } from "vue"
const msg2 = ref("這是傳給子組件的信息2")
// 或者複雜類型
const msg2 = reactive(["這是傳級子組件的信息2"])
</script>
// Child.vue 接收
<script setup>
// 不需要引入 直接使用
// import { defineProps } from "vue"
const props = defineProps({
// 寫法一
msg2: String
// 寫法二
msg2:{
type:String,
default:""
}
})
console.log(props) // { msg2:"這是傳級子組件的信息2" }
</script>注意:
如果父組件是混合寫法,子組件純 Vue3 寫法的話,是接收不到父組件裡 data 的屬性,只能接收到父組件裡 setup 函數裡傳的屬性
如果父組件是純 Vue3 寫法,子組件混合寫法,可以通過 props 接收到 data 和 setup 函數裡的屬性,但是子組件要是在 setup 裡接收,同樣只能接收到父組件中 setup 函數裡的屬性,接收不到 data 裡的屬性
官方也說了,既然用了 3,就不要寫 2 了,所以不推薦混合寫法。下面的例子,一律只用純 Vue3 的寫法,就不寫混合寫法了
2. $emit// Child.vue 派發
<template>
// 寫法一
<button @click="emit('myClick')">按鈕</buttom>
// 寫法二
<button @click="handleClick">按鈕</buttom>
</template>
<script setup>
// 方法一 適用於Vue3.2版本 不需要引入
// import { defineEmits } from "vue"
// 對應寫法一
const emit = defineEmits(["myClick","myClick2"])
// 對應寫法二
const handleClick = ()=>{
emit("myClick", "這是發送給父組件的信息")
}
// 方法二 不適用於 Vue3.2版本,該版本 useContext()已廢棄
import { useContext } from "vue"
const { emit } = useContext()
const handleClick = ()=>{
emit("myClick", "這是發送給父組件的信息")
}
</script>
// Parent.vue 響應
<template>
<child @myClick="onMyClick"></child>
</template>
<script setup>
import child from "./child.vue"
const onMyClick = (msg) => {
console.log(msg) // 這是父組件收到的信息
}
</script>
3. expose / ref父組件獲取子組件的屬性或者調用子組件方法
// Child.vue
<script setup>
// 方法一 不適用於Vue3.2版本,該版本 useContext()已廢棄
import { useContext } from "vue"
const ctx = useContext()
// 對外暴露屬性方法等都可以
ctx.expose({
childName: "這是子組件的屬性",
someMethod(){
console.log("這是子組件的方法")
}
})
// 方法二 適用於Vue3.2版本, 不需要引入
// import { defineExpose } from "vue"
defineExpose({
childName: "這是子組件的屬性",
someMethod(){
console.log("這是子組件的方法")
}
})
</script>
// Parent.vue 注意 ref="comp"
<template>
<child ref="comp"></child>
<button @click="handlerClick">按鈕</button>
</template>
<script setup>
import child from "./child.vue"
import { ref } from "vue"
const comp = ref(null)
const handlerClick = () => {
console.log(comp.value.childName) // 獲取子組件對外暴露的屬性
comp.value.someMethod() // 調用子組件對外暴露的方法
}
</script>
4. attrsattrs:包含父作用域裡除 class 和 style 除外的非 props 屬性集合
// Parent.vue 傳送
<child :msg1="msg1" :msg2="msg2" title="3333"></child>
<script setup>
import child from "./child.vue"
import { ref, reactive } from "vue"
const msg1 = ref("1111")
const msg2 = ref("2222")
</script>
// Child.vue 接收
<script setup>
import { defineProps, useContext, useAttrs } from "vue"
// 3.2版本不需要引入 defineProps,直接用
const props = defineProps({
msg1: String
})
// 方法一 不適用於 Vue3.2版本,該版本 useContext()已廢棄
const ctx = useContext()
// 如果沒有用 props 接收 msg1 的話就是 { msg1: "1111", msg2:"2222", title: "3333" }
console.log(ctx.attrs) // { msg2:"2222", title: "3333" }
// 方法二 適用於 Vue3.2版本
const attrs = useAttrs()
console.log(attrs) // { msg2:"2222", title: "3333" }
</script>
5. v-model可以支持多個數據雙向綁定
// Parent.vue
<child v-model:key="key" v-model:value="value"></child>
<script setup>
import child from "./child.vue"
import { ref, reactive } from "vue"
const key = ref("1111")
const value = ref("2222")
</script>
// Child.vue
<template>
<button @click="handlerClick">按鈕</button>
</template>
<script setup>
// 方法一 不適用於 Vue3.2版本,該版本 useContext()已廢棄
import { useContext } from "vue"
const { emit } = useContext()
// 方法二 適用於 Vue3.2版本,不需要引入
// import { defineEmits } from "vue"
const emit = defineEmits(["key","value"])
// 用法
const handlerClick = () => {
emit("update:key", "新的key")
emit("update:value", "新的value")
}
</script>
6. provide / injectprovide / inject 為依賴注入
provide:可以讓我們指定想要提供給後代組件的數據或
inject:在任何後代組件中接收想要添加在這個組件上的數據,不管組件嵌套多深都可以直接拿來用
// Parent.vue
<script setup>
import { provide } from "vue"
provide("name", "沐華")
</script>
// Child.vue
<script setup>
import { inject } from "vue"
const name = inject("name")
console.log(name) // 沐華
</script>
7. Vuex// store/index.js
import { createStore } from "vuex"
export default createStore({
state:{ count: 1 },
getters:{
getCount: state => state.count
},
mutations:{
add(state){
state.count++
}
}
})
// main.js
import { createApp } from "vue"
import App from "./App.vue"
import store from "./store"
createApp(App).use(store).mount("#app")
// Page.vue
// 方法一 直接使用
<template>
<div>{{ $store.state.count }}</div>
<button @click="$store.commit('add')">按鈕</button>
</template>
// 方法二 獲取
<script setup>
import { useStore, computed } from "vuex"
const store = useStore()
console.log(store.state.count) // 1
const count = computed(()=>store.state.count) // 響應式,會隨著vuex數據改變而改變
console.log(count) // 1
</script>
8. mittVue3 中沒有了 EventBus 跨組件通信,但是現在有了一個替代的方案 mitt.js,原理還是 EventBus
先安裝 npm i mitt -S
然後像以前封裝 bus 一樣,封裝一下
mitt.js
import mitt from 'mitt'
const mitt = mitt()
export default mitt然後兩個組件之間通信的使用
// 組件 A
<script setup>
import mitt from './mitt'
const handleClick = () => {
mitt.emit('handleChange')
}
</script>
// 組件 B
<script setup>
import mitt from './mitt'
import { onUnmounted } from 'vue'
const someMethed = () => { ... }
mitt.on('handleChange',someMethed)
onUnmounted(()=>{
mitt.off('handleChange',someMethed)
})
</script>
Vue2.x 組件通信方式Vue2.x 組件通信共有12種
父子組件通信可以用:
兄弟組件通信可以用:
跨層級組件通信可以用:
Vue2.x 通信使用寫法下面把每一種組件通信方式的寫法一一列出
1. props父組件向子組件傳送數據,這應該是最常用的方式了
子組件接收到數據之後,不能直接修改父組件的數據。會報錯,所以當父組件重新渲染時,數據會被覆蓋。如果子組件內要修改的話推薦使用 computed
// Parent.vue 傳送
<template>
<child :msg="msg"></child>
</template>
// Child.vue 接收
export default {
// 寫法一 用數組接收
props:['msg'],
// 寫法二 用對象接收,可以限定接收的數據類型、設置默認值、驗證等
props:{
msg:{
type:String,
default:'這是默認數據'
}
},
mounted(){
console.log(this.msg)
},
}
2. .sync可以幫我們實現父組件向子組件傳遞的數據 的雙向綁定,所以子組件接收到數據後可以直接修改,並且會同時修改父組件的數據
// Parent.vue
<template>
<child :page.sync="page"></child>
</template>
<script>
export default {
data(){
return {
page:1
}
}
}
// Child.vue
export default {
props:["page"],
computed(){
// 當我們在子組件裡修改 currentPage 時,父組件的 page 也會隨之改變
currentPage {
get(){
return this.page
},
set(newVal){
this.$emit("update:page", newVal)
}
}
}
}
</script>
3. v-model和 .sync 類似,可以實現將父組件傳給子組件的數據為雙向綁定,子組件通過 $emit 修改父組件的數據
// Parent.vue
<template>
<child v-model="value"></child>
</template>
<script>
export default {
data(){
return {
value:1
}
}
}
// Child.vue
<template>
<input :value="value" @input="handlerChange">
</template>
export default {
props:["value"],
// 可以修改事件名,默認為 input
model:{
event:"updateValue"
},
methods:{
handlerChange(e){
this.$emit("input", e.target.value)
// 如果有上面的重命名就是這樣
this.$emit("updateValue", e.target.value)
}
}
}
</script>
4. refref 如果在普通的DOM元素上,引用指向的就是該DOM元素;
如果在子組件上,引用的指向就是子組件實例,然後父組件就可以通過 ref 主動獲取子組件的屬性或者調用子組件的方法
// Child.vue
export default {
data(){
return {
name:"沐華"
}
},
methods:{
someMethod(msg){
console.log(msg)
}
}
}
// Parent.vue
<template>
<child ref="child"></child>
</template>
<script>
export default {
mounted(){
const child = this.$refs.child
console.log(child.name) // 沐華
child.someMethod("調用了子組件的方法")
}
}
</script>
5. $emit / v-on子組件通過派發事件的方式給父組件數據,或者觸發父組件更新等操作
// Child.vue 派發
export default {
data(){
return { msg: "這是發給父組件的信息" }
},
methods: {
handleClick(){
this.$emit("sendMsg",this.msg)
}
},
}
// Parent.vue 響應
<template>
<child v-on:sendMsg="getChildMsg"></child>
// 或 簡寫
<child @sendMsg="getChildMsg"></child>
</template>
export default {
methods:{
getChildMsg(msg){
console.log(msg) // 這是父組件接收到的消息
}
}
}
6.