【发布时间】:2020-05-01 13:12:27
【问题描述】:
我无法使用 ref='menu' 访问子元素方法 prom 父元素。当我尝试在 Vue 应用程序元素中的按钮 el 中调用 $refs.menu.show 时,一切正常,在照片 el 中它不起作用。在父 Vue 应用程序中注册的所有组件。
//ERROR
vue.js:634 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'show' of undefined"
found in
---> <Photo>
<Root>
我在#app 中的 HTML 代码
// For tests
<button @click.prevent='$refs.menu.show'></button>
<div class="center" :style="{ width : center_div_width+'px', height : window_height+'px'}">
<template v-for='(row, index1) in info'>
// Parent element
<photo v-for="(item, index2) in row" :item="item" :art_width='art_width'>
// Child element
<cmenu ref='menu'>
<li>Test</li>
<li>Test2</li>
</cmenu>
</photo>
</template>
</div>
// JS
我的组件。 我正在尝试从“照片”组件的模板调用嵌套应用程序方法:
Vue.component('photo', {
props: ['item', 'art_width'],
template: `<a class='art' href="" :style="offset(item.offsetX, item.offsetY)" @mouseover="hover = true" @mouseout="hover = false">
<img v-bind:src="/media/ + item.path" class="img" :width="art_width+'px'">
<a href="" class='art-owner' align="center" v-show='hover'>{{item.owner}}</a>
<a href="" class='art-menu' align="center" v-show='hover' @click.prevent='$refs.menu.show'>...</a>
<slot></slot>
</a>`,
data: function () {
return {
hover: false,
}
},
methods: {
offset (valueX, valueY) {
return `transform: translateX(${ valueX }) translateY(${ valueY })`
},
},
})
context_menu = Vue.component('cmenu', {
template: `<div class='context-menu'>
<ul>
<slot></slot>
</ul>
</div>`,
data: function () {
return {
ifshow: false,
style = null
}
},
mounted() {
window.addEventListener('click', (event) => {
if (Object.is($el, event.target) == true) {
this.ifshow = false;
}
});
},
methods: {
show: function(event) {
this.ifshow = true;
}
}
})
【问题讨论】:
标签: javascript vue.js