vue.js 如何通过阅读json数据来使用v-for?

ccgok5k5  于 2022-11-25  发布在  Vue.js
关注(0)|答案(1)|浏览(171)

我想使用v-for通过阅读json数据来生成一些<li>元素。
这是我代码,json urls作为数据。

<script>
    const urls =[
        {text:'math',href:'math',icon:'bi bi-calculator'},
        {text:'chemistry',href:'chemistry',icon:'bi bi-boxes'},
    ]
</script>

<template lang="ejs">
    
    <nav class="navbar navbar-light navbar-expand-md py-3" style="background: rgb(89,154,143);">
        <div class="container">
            <div class="collapse navbar-collapse" id="navcol-2">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item" v-for="(item, index) in urls">
                        <a class="nav-link link-light" href=${item.href}><i class="${item.icon}"></i>${item.href}</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</template>

但它返回

[eslint] 
D:\+coding\webpagetools2.0\src\components\navBar.vue
  2:11  error  'urls' is assigned a value but never used  no-unused-vars

urls json数据好像没有包含在模板中,而是包含在脚本中,如何解决?
我已经试过动

const urls =[
        {text:'數學工具',href:'math',icon:'bi bi-calculator'},
        {text:'化學工具',href:'chemistry',icon:'bi bi-boxes'},
    ]

到模板节,但它不起作用。

vwkv1x7d

vwkv1x7d1#

看起来您正在尝试使用脚本设置语法,但脚本标记中缺少setup属性:

<script setup>
    const urls =[
        {text:'math',href:'math',icon:'bi bi-calculator'},
        {text:'chemistry',href:'chemistry',icon:'bi bi-boxes'},
    ]
</script>

建议使用refreactive将变量定义为React属性:

<script setup>
  import {ref} from 'vue'
  
  const urls =ref([
        {text:'math',href:'math',icon:'bi bi-calculator'},
        {text:'chemistry',href:'chemistry',icon:'bi bi-boxes'},
    ])
</script>

相关问题