-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
97 lines (87 loc) · 2.03 KB
/
index.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function contextToken(name) {
return typeof Symbol === 'function' ? Symbol(name) : name + Math.random()
}
Vue.mixin({
beforeCreate() {
if (!this.$options.expose) return
const computed = this.$options.computed || {}
computed.$context = () => this.$options.expose.call(this, this)
this.$options.computed = computed
}
})
Vue.mixin({
beforeCreate() {
if (!this.$options.inject) return
const computed = this.$options.computed || {}
for (let key of Object.keys(this.$options.inject)) {
const token = this.$options.inject[key]
computed[key] = () => this.$inject({token})
}
this.$options.computed = computed
},
methods: {
$inject({token, all}) {
let parent = this
let ret = []
while (parent) {
const $context = parent.$context
if ($context && $context.hasOwnProperty(token)) {
if (all) ret.push($context[token])
else return $context[token]
}
parent = parent.$parent
}
return all ? ret : undefined
}
}
})
// example
var user = contextToken('user')
var anotherUser = contextToken('user')
var allUser = contextToken('allUser')
Vue.component('parent', {
template: `
<div>
<button @click="user.name += 1">+1</button><br/>
Child in template: <child></child>
Man in the middle: <mitm></mitm>
<slot></slot>
</div>`,
data() {
return {
user: {
name: 'Sebastian ',
},
}
},
expose: (vm) => ({
[user]: vm.user,
[allUser]: vm.user.name
})
})
Vue.component('mitm', {
template: `<child></child>`,
data() {
return {
user: {
name: 'Deyne',
}
}
},
expose() {
let name = this.user.name
return {
[anotherUser]: this.user,
[allUser]: name
}
}
})
Vue.component('child', {
template: '<div>{{ user.name }} in {{$inject({token: allUser, all: true})}}</div>',
data: () => ({allUser}),
inject: { user }
})
new Vue({
el: '#app',
template: '<parent>Another child in slot: <child></child></parent>'
})