技术栈总结-vue
gyh 2020-08-10 vue
# vue
# Bus 原理
class Bus {
constructor() {
// {
// eventName1:[fn1,fn2],
// eventName2:[fn3,fn4],
// }
this.callbacks = {}
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit(name, args) {
if (this.callbacks[name]) {
// 存在 遍历所有callback
this.callbacks[name].forEach(cb => cb(args))
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 在组件上使用 v-model
自定义事件也可以用于创建支持 v-model 的自定义输入组件。记住:
<input v-model="searchText" />
1
等价于:
<input :value="searchText" @input="searchText = $event.target.value" />
1
当用在组件上时,v-model 则会这样:
<custom-input :model-value="searchText" @update:model-value="searchText = $event"></custom-input>
1
为了让它正常工作,这个组件内的 <input>
必须:
将其 value attribute 绑定到一个名叫 modelValue 的 prop 上 在其 input 事件被触发时,将新的值通过自定义的 update:modelValue 事件抛出 写成代码之后是这样的:
app.component('custom-input', {
props: ['modelValue'],
emits: ['update:modelValue'],
template: `
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
>
`,
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
现在 v-model 就应该可以在这个组件上完美地工作起来了:
<custom-input v-model="searchText"></custom-input>
1