# 快速上手

# 依赖要求

提示

此包依赖于 Vue 2。请确保在安装此包之前,你的项目中已经安装了 Vue 2。

本文会帮助你从头使用vue2-context。

  1. 安装vue2-context
yarn add vue2-context -S
// 或
npm install vue2-context -S
1
2
3
  1. 创建上下文实例
import { createContext } from 'vue2-context';
export const chatContext = createContext();
1
2
  1. 父级组件
<template>
  <ChatContextProvider :value="hello">
    parent: {{ hello.val }}
    <Child />
    <button @click="hello.val++">++</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: {
        val: 0
      }
    }
  },
}
</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
  1. 子级组件
<template>
  <div>
    child : {{ context.value.val }}</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
17
parent: 0
child : 0

WARNING

如果传入的是一个基本数据类型,请使用.value,以保证能够响应