多组件对应同数据源处理(provide,inject)
# 多组件对应同数据源处理(provide,inject)
单个组件同时修改使用单个数据源的情况 例如 接口返回的一个大对象,三个组件分别对应对象内部分数据,这种情况下使用provide,inject就会很方便舒适
<template>
<div>
<ChildComponent />
<ChildComponent1 />
<ChildComponent2 />
</div>
</template>
<script>
import { provide, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
import ChildComponent1 from './ChildComponent.vue';
import ChildComponent2 from './ChildComponent.vue';
export default {
components: {
ChildComponent,
ChildComponent1,
ChildComponent2
},
setup() {
const data = ref('initial value');
provide('data', data);
return {
data
};
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<div>
<p>{{ data }}</p>
<button @click="updateData">Update Data</button>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
setup() {
const data = inject('data');
const updateData = () => {
data.value = 'Updated value';
};
return {
data,
updateData
};
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
上次更新: 2024/05/06, 13:13:30