CONTEXT
React context API like Implementation in Vue.
Context provides a way to pass data through the component instance tree without having to pass props down manually at every level.
When to Use Context
You should always take into consideration of Store first.
It will be necessary when you find the dependency between components and Store make it difficult for you to decouple your project into components.
Getting Start
- Install vis npm,
npm install --save context.vue
- Install to Vue as a plugin
import Context from 'context.vue'
Vue.use(Context)
Now the method this.$createContext
is in your component, and components Provider
and Consumer
are available.
Usage
For example, in the code below we manually thread through a “theme” prop in order to style the Button component:
@Component({
props: {
theme: String,
},
})
class ThemedButton extends Vue {
render(h) {
return <Button theme={this.theme}></Button>
}
}
@Component({})
class Layout extends Vue {
data() {
return { theme: 'dark' }
}
render(h) {
return <ThemedButton theme={this.theme}></ThemedButton>
}
}
Using context, we can avoid passing props through intermediate elements:
@Component({
template: `
<consumer>
<template slot-scope="{ theme }">
<button :theme="theme"></button>
</template>
</consumer>`,
})
class ThemedButton extends Vue {
}
@Component({})
class Layout extends Vue {
data() {
return {
state: this.$createContext({
theme: 'dark',
}),
}
}
render(h) {
return (
<provider value={this.state}>
<ThemedButton></ThemedButton>
</provider>
)
}
}
Examples
Updating Context from a Nested Component
themed-button.vue
<template>
<consumer>
<template slot-scope="{ theme, dispatch }">
<button :theme="theme" @click="dispatch('changeTheme', 'red')"></button>
</template>
</consumer>
</template>
layout.vue
<template>
<provider :value="state">
<themed-button></themed-button>
</provider>
</template>
<script>
export default {
data() {
return {
state: this.$createContext({
theme: 'dark',
}, {
changeTheme(context, color) {
context.theme = color
},
}),
}
},
}
</script>
Consuming Multiple Contexts
If you have to implement this, please use Vuex
instead of Context API,