【问题标题】:Vue component access data objectVue组件访问数据对象
【发布时间】:2016-08-14 17:41:17
【问题描述】:

如何检查对象在计算属性中是否有子元素 前任。 https://jsfiddle.net/zvku6voo/

我需要在点击时检查子菜单功能,在加载页面上并通过默认打开子菜单,我如何访问子菜单功能上的当前对象?

HTML 和模板:

<template id="ids-sidebar-menu-template">
    <li v-for="li in list" >
        <a href="@{{ li.url }}" @click="toggle" >
            @{{li.title}}
            <span v-if="submenu" class="right"> + </span>
        </a>
        <ul v-show="open" v-if="submenu">
            <ids-sidebar-menu :list="li.children"></ids-sidebar-menu>
        </ul>
    </li>
</template>   

Vue 组件:

Vue.component('ids-sidebar-menu', {
    template : '#ids-sidebar-menu-template',
    props: {
        list : Array
    },
    data: function () {
        return {
            open: false
        }
    },
    computed: {
        submenu: function () {
                return true;
                // problem here
            return this.children && this.children.length
        }
    },
    methods: {
        toggle: function (e) {
            e.preventDefault();
            if (this.submenu)
                this.open = !this.open
        }
    }
});

数据:

var data = [
    {
        title : 'Title 1',
        url : '#',
        children: [
            {
                title : 'Subtitle 1',
                url : '#'
            },
            {
                title : 'Subtitle 2',
                url : '#'
            },
            {
                title : 'Subtitle 3',
                url : '#'
            }
        ]
    },
    {
        title : 'Title 2',
        url : '#'
    }
];

Vue:

var vm = new Vue({
    el : '#sidebar-menu',
    data: {
        links: data
    }
});

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    问题是您将整个列表传递给每个&lt;ids-submenu-item&gt; 组件。每个子菜单项组件应该只传递它需要显示的项目,而不是所有的链接。工作小提琴:https://jsfiddle.net/zvku6voo/2/

    <ul id="sidebar-menu">
        <ids-sidebar-menu v-for="item in links" :line="item"></ids-sidebar-menu>
    </ul>
    
    <template id="ids-sidebar-menu-template">
        <li>
            <a href="{{ line.url }}" @click="toggle" >
                {{line.title}}
                <span v-if="submenu" class="right"> + </span>
            </a>
            <ul v-show="open" v-if="submenu">
                <ids-sidebar-menu v-for="item in line.children" :line="item"></ids-sidebar-menu>
            </ul>
        </li>
    </template>
    

    js:

    props: {
            line : Object
        },
        data: function () {
            return {
                open: false
            }
        },
        computed: {
            submenu: function () {
                return this.line.children && this.line.children.length
            }
        },
    

    【讨论】:

    • 如何添加默认活动项或子菜单项并在加载时打开?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2018-08-03
    • 2017-10-17
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多