二.Vue3.x(通信)
前言
补充一些官方文档中没有的,但是实际开发中最好需要了解的内容
1. props
父组件数据
<template>
<ChildComponent :parentData="parentData" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './vue-message1-1.vue';
const parentData = ref('父组件数据');
</script>
2. $emit
父组件数据
<template>
<ChildComponent :parentData="parentData" />
</template>
<script setup >
import { ref } from 'vue';
import ChildComponent from './vue-message2-1.vue';
const parentData = ref('父组件数据');
</script>
js
const props = withDefaults(
defineProps<{
lotteryList: { pic: string; name?: string }[];
winId: number;
initSpeed: number;
fastSpeed: number;
slowSpeed: number;
baseCircles: number;
classPrefix: string;
}>(),
{
lotteryList: () => [],
winId: 0,
initSpeed: 300,
fastSpeed: 100,
slowSpeed: 600,
baseCircles: 4,
}
);这里的withDefaults是什么?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
3. expose / ref
<template>
<child ref="comp"></child>
<el-button @click="handlerClick">按钮</el-button>
</template>
<script setup>
import { ref } from "vue";
import child from "./vue-message3-1.vue";
const comp = ref(null);
const handlerClick = () => {
console.log(comp.value.childName); // 获取子组件对外暴露的属性
comp.value.someMethod(); // 调用子组件对外暴露的方法
};
</script>
4. attrs
a:1
a:1
x:100
y:200
<template>
<h4>a:{{ a }}</h4>
<Child :a="a" v-bind="{x:100,y:200}" :updateA="updateA"/>
</template>
<script setup >
import {ref} from 'vue'
import Child from './vue-message4-1.vue'
let a = ref(1)
function updateA(value) {
a.value += value
}
</script>
5. v-model
<template>
<child ref="comp"></child>
<el-button @click="handlerClick">按钮</el-button>
</template>
<script setup>
import { ref } from "vue";
import child from "./vue-message5-1.vue";
const comp = ref(null);
const handlerClick = () => {
console.log(comp.value.childName); // 获取子组件对外暴露的属性
comp.value.someMethod(); // 调用子组件对外暴露的方法
};
</script>
6. provide / inject
宝马10
<template>
<div>{{ parentData }}</div>
<ChildComponent></ChildComponent>
</template>
<script setup>
import {ref, reactive, provide} from 'vue'
import ChildComponent from './vue-message6-1.vue';
let money = ref(100)
let car = reactive({
brand: '宝马',
price: 10
})
function updateMoney(value) {
money.value -= value
}
// 向后代提供数据
provide('moneyContext', {money, updateMoney})
provide('car', car)
</script>
7. Vuex
8.mitt
- 1.首先全局引入
js
import { createApp } from "vue";
const app = createApp({});
import mitt from "mitt";
app.config.globalProperties.$bus = mitt();
app.provide("$bus", $bus);
1
2
3
4
5
2
3
4
5
- 2.订阅数据
js
...
setup(){
const $bus = inject("$bus")
$bus.on('customEvent', () => console.log('i got customEvent')
}
...
1
2
3
4
5
6
2
3
4
5
6
- 3.发布数据
js
...
setup(){
const $bus = inject("$bus")
$bus.emit("customEvent");
}
...
1
2
3
4
5
6
2
3
4
5
6