无法从父级访问嵌套元素

时间:2020-05-01 13:12:27

标签: javascript vue.js

我无法使用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;
            }
        }
    })

1 个答案:

答案 0 :(得分:1)

ref用于注册对元素或子组件的引用。该引用将被注册在父组件的$refs对象下。

photo组件具有自己的作用域和自身的$refs