use

使用场景

如果你想用vue2-context传递theme是完全可行的,你可以用它做多层嵌套,vue2-context会自动为你寻找最近的父级,并获取其映射的可变值

  1. 创建一个ThemeDisplay组件
p.js
Copy

_3
<template>
_3
<div :class="context.value">theme display: {{ context.value }}</div>
_3
</template>

  1. 在父组件中使用Provider包裹

_13
<NestContextProvider :value="theme">
_13
<Child />
_13
</NestContextProvider>
_13
_13
<script>
_13
...
_13
data() {
_13
return {
_13
theme: 'dark'
_13
}
_13
}
_13
...
_13
</script>

  1. 在子组件中使用Provider包裹一层

_17
<div :class="context.value" style="padding: 10px;">
_17
<ThemeDisplay />
_17
<NestContextProvider :value="childTheme">
_17
<ThemeDisplay />
_17
</NestContextProvider>
_17
</div>
_17
_17
<script>
_17
...
_17
data() {
_17
return {
_17
context: useContext(nestContext, this),
_17
childTheme: 'light',
_17
}
_17
}
_17
...
_17
</script>

即可获得如下效果