虽然从技术上讲可以访问$refs
个嵌套的子对象...
Vue.component('mycomponent', {
template: "#mycomponent",
});
new Vue({
el: '#app',
mounted() {
console.log(
'Second level <input>\'s value:',
this.$refs.myFirstLevelRefName.$refs.mySecondLevelRefName.value
)
}
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<template id="mycomponent">
<div>
<input ref="mySecondLevelRefName" value="Hello">
</div>
</template>
<div id="app">
<mycomponent ref="myFirstLevelRefName"></mycomponent>
</div>
对于简单场景,执行父/深子或深祖先/sibling 姐妹通信的一种方法是使用event hub.(有关复杂场景,请参见Vuex.)
您将创建一个全局变量:
var eventHub = new Vue(); // use a Vue instance as event hub
要发出在任何组件中使用的事件,请执行以下操作:
eventHub.$emit('myevent', 'some value');
那么,在任何其他部分中,你都可以听到这个事件.该活动的活动可以是任何形式,包括method call分(这是您想要的):
eventHub.$on('myevent', (e) => {
console.log('myevent received', e)
// this.callSomeMethod();
});
Demo:
var eventHub = new Vue(); // use a Vue instance as event hub
Vue.component('component-first', {
template: "#component-1st",
methods: {
myMethod() {
eventHub.$emit('myevent', 'some value');
}
}
});
Vue.component('component-second', {template: "#component-2nd"});
Vue.component('component-third', {
template: "#component-3rd",
created() {
eventHub.$on('myevent', (e) => {
this.check();
});
},
methods: {
check() {
console.log('check method called at 3rd level child');
}
}
})
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<template id="component-1st">
<div>
1st level component
<button @click="myMethod">Trigger event at 1st level component that will call 3rd level child's method</button>
<hr>
<component-second></component-second>
</div>
</template>
<template id="component-2nd">
<div>
<component-third></component-third>
</div>
</template>
<template id="component-3rd">
<div><h1>3rd level child</h1></div>
</template>
<div id="app">
<component-first></component-first>
</div>
Note:如果在您的环境中创建一个专用实例作为事件中心是件复杂的事情,那么您可以将eventHub
替换为this.$root
(在组件内部),并使用您自己的Vue实例作为中心.