vue render 使用JSX如何实现 v-for 功能呢?

现在使用iView 的 Notice组件做一个通知的浮动层。要求这个面板内容里面是后台请求的list里的数据。用JSX 没有办法使用 v-for指令 ,那么这里的列表怎么渲染出来呢。。。

代码如下:
export default({

    data() {
        return {
            noticeList: []//接口返回的list
        }
    },
    methods: {
        showInformList() {
            this.$Notice.open({
                title:'通知',
                desc:'这个会被隐藏',
                duration:0,
                render(){
                    return (
                        <div>
                            <ul>
                                **<li v-for =(item,index) in noticeList> {{item.name}}</li>**
                                //这里无法使用v-for渲染出li
                            </ul>
                        </div>
                    )
                }
            })
        }
  }

})

想要实现的效果如下:

clipboard.png

阅读 24.8k
5 个回答
return (
    <div>
        <ul>
            {
                this.noticeList.map(item => {
                    return <li>{item.name}</li>
                })
            }
        </ul>
    </div>
)

jsx实现循环的话,一般是使用map实现,你可以看下react是如何实现的,react都是基于jsx的,大致如下:

<ul>
    {
        noticeList.map(item => <li>{item.name}</li>)
    }
</ul>

这种

现在使用了另一种思路实现这个效果,没有直接使用JSX渲染出列表,而是自定义一个通知面板的内容组件,在这个组件上正常的取数据渲染数据。 再通过render函数把这个组件渲染进Notice组件。

代码如下:

    name: 'Notice',
    components: {
        noticeContent
    },
    data() {
        return {
        }
    },

    methods: {
        showInformList() {
            this.$Notice.open({
                title: '通知',
                desc: '这个会被隐藏',
                duration: 0,
                render(h) {
                    return h(noticeContent)
                }
            })
        }
    }

noticeContent组件内容大致如下:

<template>
<div class="notice-list-content">
    <div class="ul-style">
        <div **v-for="(item,index) in noticeList"** class="li-style">
            <div class="first-line-box">
                <div class="first-line">{{item.name}}</div>
                <div class="first-line">{{item.title}}</div>
                <div class="first-line">{{item.level}}</div>
            </div>
            <div class="second-line-box">
                <div>{{item.time}}</div>
            </div> 
        </div>
    </div>
</div>
</template>
//script里面正常掉接口取数即可

虽然没有通过JSX来生成列表内容,但是同样实现了效果。并且这种方式对于Notice组件内部内容样式复杂时也能很好的适应。毕竟直接写template还是更加直观简单呀。

render(h) {
    var list = [1, 2, 3]
    return (
        <div>
            {
                list.map(item => {
                    return <button>按钮{item}</button>
                })
            }
        </div>
    )
}

要注意<div> </div>不能去掉,外边必须得包一层,不知道为什么

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题