# 快速上手
# 依赖要求
提示
此包依赖于 Vue 2。请确保在安装此包之前,你的项目中已经安装了 Vue 2。
本文会帮助你从头使用 vue2-context。
- 安装 vue2-context
yarn add vue2-context -S
// 或
npm install vue2-context -S
1
2
3
2
3
- 创建上下文实例
import { createContext } from "vue2-context";
export const chatContext = createContext();
1
2
2
- 父级组件
<template>
<ChatContextProvider :value="{ hello }">
parent: {{ hello }}
<Child />
<button @click="hello++">++</button>
</ChatContextProvider>
</template>
<script>
import Child from "./Child.vue";
import { chatContext } from "./config";
const ChatContextProvider = chatContext.Provider;
export default {
components: { ChatContextProvider, Child },
data() {
return {
hello: 0,
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- 子级组件
<template>
<div>child : {{ context.value.hello }}</div>
</template>
<script>
import { useContext } from "vue2-context";
import { chatContext } from "./config";
export default {
data() {
return {
context: useContext(chatContext, this),
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
WARNING
如果传入的是一个基本数据类型,请使用.value
,以保证能够响应