Home  >  Q&A  >  body text

javascript - KnockoutJs如何实现组件递归,实现树形列表?

我想实现这样的例子:http://cn.vuejs.org/examples/...
它是用vue实现的,用ko的怎么做到?
我的数据结构类似这样(层级不确定):

var data=[
                {
                    id:1,
                    "text": "111-1",
                    "children": []
                }, 
                {
                    id:2,
                    "text": "111-2",
                    "children": [
                    {
                        id:2-1,
                        "text": "111-2-1",
                        "children": [
                            {
                                id:2-1-1,
                                "text": "111-2-1-1",
                                "children": [
                                    {
                                        id:2-1-1-1,
                                        "text": "111-2-1-1-1",
                                        "children": []
                                    }
                                ]
                            },
                            {
                                id:2-1-2,
                                "text": "111-2-1-2",
                                "children": []
                            }
                        ]
                    }, 
                    {
                        id:2-2,
                        "text": "111-2-2",
                        "children": []
                    },                     
                    {
                        id:2-3,
                        "text": "111-2-3",
                        "children": []
                    }
                    ]
                }
            ]

请大神们指教。

ringa_leeringa_lee2767 days ago610

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-11 09:01:35

    父组件中

    <items  :model='model' v-for='model in data'></items>

    子组件 记住vue中递归组件给name属性 按照name递归循环

    <template>
        <li >
            <p @click='toggle'>
                {{model.id}}<span v-if='isFolder'>[{{open?"-":"+"}}]</span>
            </p>
            <ul v-show="open" v-if='isFolder'>
                <items v-for='cel in model.children' :model='cel' ></items>
            </ul>
        </li>
    </template>
    <script type="text/javascript">
        export default{
            name:'items',
            props:['model'],
            components: {
            },
            data(){
                return{
                    open:false,
                    isFolder:true
                }
            },
            computed: {
               isFolder:function(){
                    return this.model.children && this.model.children.length
                }
            },
            methods:{
                toggle:function(){
                    if(this.isFolder){
                        this.open=!this.open
                    }
                },
            }
        }
    </script>

    reply
    0
  • Cancelreply