V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
imherer
V2EX  ›  程序员

请教前端大佬一个 Vue.js 问题

  •  
  •   imherer · 290 天前 · 1322 次点击
    这是一个创建于 290 天前的主题,其中的信息可能已经有所发展或是发生改变。

    不会前端,最近用现成的框架改点东西,我想通过 h 动态渲染一些 html 标签应该如何实现

     return h(
         <div>
             <h1 style="font-size:30px">1</h1>
             <h1 style="font-size:30px">2</h1>
             <h1 style="font-size:30px">3</h1>
         </div>
         )
    

    例如上面的代码,div 里面的 h1 标签数量不确定,是通过一个数组来决定的,类似于这样

    const arrList = [1, 2, 3]
        
    <div v-for="item in arrList">
        <h1 style="font-size:30px">{item}</h1>
    </div>
          
    

    这个应该怎么写呢

    10 条回复    2023-07-13 16:34:47 +08:00
    chensuiyi
        1
    chensuiyi  
       290 天前
    如果可以,能不能不用 h 函数实现呢。。
    shakukansp
        2
    shakukansp  
       290 天前   ❤️ 1
    h('div', arrList.map( i => h('h1', { style:'font-size:30px' }, [i]) ))
    imherer
        3
    imherer  
    OP
       290 天前
    @chensuiyi emmm ,谢谢你提醒,我好像知道怎么做了。我试试
    imherer
        4
    imherer  
    OP
       290 天前
    @shakukansp 感谢大佬,这个是可行的
    lianyue
        5
    lianyue  
       290 天前   ❤️ 1
    ```html
    <template>
    <AppBar></AppBar>
    </template>
    <script setup lang="ts">
    const arrList = [1, 2, 3]

    let children = []
    for (let i = 0; i < arrList.length; i++) {
    const item = arrList[i];
    children.push(h('h1', { style: 'font-size:30px' }, String(item)))

    }
    const AppBar = h('div', {class:'h-div'}, children)
    </script>
    ```
    xinfushuo123
        6
    xinfushuo123  
       290 天前
    如果可以用 jsx 的话 试试 v-for
    Laobai
        7
    Laobai  
       290 天前
    v-for 直接写在 h1 标签上就行了吧,对了记得加 key
    anonydmer
        8
    anonydmer  
       290 天前
    虽然技术上没有问题,但是从语义上来说不应该包含多个 h1 吧
    waiaan
        9
    waiaan  
       290 天前
    vue 不是支持 jsx 语法吗?
    Yukiteru
        10
    Yukiteru  
       290 天前   ❤️ 1
    这个没必要用渲染函数,是基础中的基础,直接 v-for 循环渲染就好了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5280 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 05:46 · PVG 13:46 · LAX 22:46 · JFK 01:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.