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

如何通过edition?section=1#s1格式的URL导航至对应Vue组件内容?

解决方案

你使用的window.location.search({ section: index })写法错误,window.location.search是用于获取当前URL查询参数的只读字符串属性,并非可调用方法,因此无法完成参数修改和URL更新,可选择以下两种方案实现需求:


方案1:原生JS实现(无需引入Vue Router)

步骤1:编写菜单点击事件逻辑

点击故事项时,通过history.pushState实现无刷新更新URL,同时切换展示内容:

// 点击故事项的处理函数,入参为:章节索引sectionIndex、故事锚点标识storyId
function handleStoryClick(sectionIndex, storyId) {
  // 构造目标URL
  const targetUrl = new URL(window.location.href)
  targetUrl.searchParams.set('section', sectionIndex)
  targetUrl.hash = `#s${storyId}`
  // 无刷新更新地址栏URL
  window.history.pushState({}, '', targetUrl)
  // 切换展示对应章节内容
  this.currentSection = this.navigation.section[sectionIndex]
  // 可选:自动滚动到对应故事位置
  document.querySelector(targetUrl.hash)?.scrollIntoView()
}

步骤2:页面初始化/前进后退时自动同步内容

mounted() {
  // 页面加载时读取URL参数自动加载对应内容
  const initUrl = new URL(window.location.href)
  const sectionIndex = initUrl.searchParams.get('section')
  const storyHash = initUrl.hash
  if (sectionIndex && this.navigation.section[sectionIndex]) {
    this.currentSection = this.navigation.section[sectionIndex]
    storyHash && document.querySelector(storyHash)?.scrollIntoView()
  }
  // 监听浏览器前进后退操作,同步更新内容
  window.addEventListener('popstate', () => {
    const url = new URL(window.location.href)
    const sectionIndex = url.searchParams.get('section')
    sectionIndex && this.navigation.section[sectionIndex] && (this.currentSection = this.navigation.section[sectionIndex])
  })
}

方案2:Vue Router实现(适合已接入路由的单页应用)

步骤1:配置路由规则

// router/index.js 路由配置
const routes = [
  {
    path: '/edition',
    name: 'EditionPage',
    component: () => import('@/views/Edition.vue')
  }
]

步骤2:点击故事项触发路由跳转

// 点击故事项的处理函数
function handleStoryClick(sectionIndex, storyId) {
  this.$router.push({
    path: '/edition',
    query: { section: sectionIndex },
    hash: `#s${storyId}`
  })
}

步骤3:监听路由参数自动更新内容

watch: {
  '$route': {
    handler(route) {
      const sectionIndex = route.query.section
      if (sectionIndex && this.navigation.section[sectionIndex]) {
        this.currentSection = this.navigation.section[sectionIndex]
        route.hash && document.querySelector(route.hash)?.scrollIntoView()
      }
    },
    immediate: true // 页面首次加载自动触发
  }
}

适配建议

你当前定义的navigation.section是对象结构,v-for遍历对象时顺序不固定,建议将navigation.section调整为数组结构,或者给每个section配置固定的唯一ID作为参数值,避免索引匹配错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:57:03