<template>
  <nav>
    <ul>
      <li v-for='(item, index) in menuItems' :key='index'>
        <router-link :to='item.link'>{{ item.label }}</router-link>
      </li>
    </ul>
  </nav>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      menuItems: [],
    };
  },
  mounted() {
    axios.get('/api/menu') // 假设后端 API 的路由是 /api/menu
      .then(response => {
        this.menuItems = response.data;
      })
      .catch(error => {
        console.log(error);
      });
  },
};
</script>
<p>以上代码中,组件首先定义了一个空的 <code>menuItems</code> 数组用于存储从后端 API 获取的菜单数据。在组件的 <code>mounted</code> 钩子函数中,使用 <code>axios</code> 库从后端 API 获取数据。假设 API 返回的数据结构如下:</p>
<pre><code>[
  { label: '首页', link: '/' },
  { label: '新闻', link: '/news' },
  { label: '关于我们', link: '/about' },
]
</code></pre>
<p>然后,使用 <code>v-for</code> 指令在模板中循环渲染菜单项,并使用 <code>router-link</code> 组件将其链接到相应的页面。</p>
<p>需要注意的是,以上代码仅为示例,并不适用于所有情况。具体实现可能需要根据具体情况进行调整。</p>

原文地址: https://www.cveoy.top/t/topic/mAJ1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录