You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中使用@click.prevent后页面内容无法显示的问题求助

Vue 3点击导航不切换内容的问题排查与解决

问题根源

  • 非响应式变量导致视图不更新:setup中直接返回的activePage是普通数值,Vue 3不会追踪其变化,修改后页面无法触发重新渲染。
  • 挂载目标冲突:挂载到<body>会和Bootstrap的DOM结构产生冲突,导致事件绑定失效或数据更新异常。
  • 导航激活状态未动态处理:所有链接固定带有active类,无法体现当前选中状态,也不符合交互逻辑。

修复步骤

  1. 将activePage转为响应式变量:
    在setup中导入ref,用ref()包裹变量,修改时通过.value访问。
  2. 使用独立挂载容器:
    在<body>内创建一个<div id="app">容器,把所有需要Vue管理的DOM放入其中,挂载时指向#app。
  3. 动态绑定导航激活类:
    通过:class指令根据activePage和当前循环的index判断是否添加active类。

修正后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue Basics</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
  <script src="https://unpkg.com/vue@3"></script>
</head>
<body>
  <div id="app">
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
      <div class="container-fluid">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li v-for="(value, index) in pages" class="nav-item" :key="index">
              <a 
                class="nav-link" 
                :class="{ active: activePage === index }"
                aria-current="page" 
                :href="value.link.url"
                :title="`This link goes to the ${value.link.text} page`"
                @click.prevent="activePage = index"
              >{{value.link.text}}</a>
            </li>
          </ul>
      </div>
    </nav>
    <div id="content" class="container">
      <h1>{{ pages[activePage].pageTitle }}</h1>
      <p>{{ pages[activePage].content }}</p>
    </div>
  </div>

  <script>
  const { createApp, ref} = Vue

  createApp({
    setup() {
      const activePage = ref(0)
      const pages = [
        {
          link: {text: 'Home', url:'index.html'},
          pageTitle : 'Hello, Vue',
          content: 'Welcome to the world of vue'
        },
        {
          link: {text: 'Link', url:'link.html'},
          pageTitle : 'Hello, Vue',
          content: 'This is the link text'
        },
        {
          link: {text: 'Contact', url:'contact.html'},
          pageTitle : 'Hello',
          content: 'This is the contact page'
        }
      ]
      
      return {
        activePage,
        pages
      }
    }
  }).mount('#app');
  </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:23:15