vue trigger component

简单粗暴

1
2
3
4
5
6
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>

var child = this.$refs.profile;
child.x();

总线

in main.js

1
export const bus = new Vue()

in Parent.vue:

1
import {bus} from 'path/to/main'

// Where you wanna call the child’s method:

1
bus.$emit('customEventName', optionalParameter)

in Child.vue:

1
import {bus} from 'path/to/main'

// Add this to the mounted() method in your component options object:

1
bus.$on('customEventName', this.methodYouWannaCall)

总线代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import ChildForm from './components/ChildForm'

new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})

组件代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template> </template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>

$attrs

组件内,返回 除 class style props 以外的 其他属性

1
console.log(this.$attrs);

$children

1
console.log(this.$root.$children[0].$children[0].$data);

$createElement:

$el:

$listeners:

$options:

$root:

$scopedSlots:

$slots:

$vnode:

event bus 多次触发

$on 的事件可在 created 或 mounted 注册

需在 beforeDestroy 或 destoryed 的时候使用用 $off 销毁

否则在某些情况下会被被多次触发

this.EventBus.$off(‘map_is_ready’);

全部 cancel

this.EventBus.$off();