gpt4 book ai didi

javascript - 动态路由上的 Vue.js 2.0 转换未触发

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:52 24 4
gpt4 key购买 nike

我发现转换不会在带参数的动态路由上触发。例如下面的代码,当我在 /chapter/1 并转到 /chapter/2 时,没有转换。但是当我在 /chapter/1 并转到 /profile/1 时,有一个!

main.js 文件

require('normalize.css')

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
import Panel from './components/Panel'
import Profile from './components/Profile'

window.bus = new Vue()

Vue.use(VueRouter)

const router = new VueRouter({
routes: [
{ path: '/', redirect: '/chapter/1' },
{ name:'chapter', path: '/chapter/:id', component: Panel},
{ name:'profile', path: '/profile/:id', component: Profile}
]
})

new Vue({
router,
el: '#app',
render: h => h(App)
})

App.vue 模板

<template>
<div id="app">

<transition name="fade" mode="out-in">
<router-view></router-view>
</transition>

<div class="controls">
<router-link :to="{ name: 'chapter', params: { id: Math.max(1, parseInt($route.params.id) - 1) }}">
Prev
</router-link>
<router-link :to="{ name: 'chapter', params: { id: parseInt($route.params.id) + 1 }}">
Next
</router-link>
</div>
</div>
</template>

可能是因为 vue-router 没有销毁父组件?我没有找到从代码运行转换的方法。我在 vue-router example pack 上试过这个配置并且行为是相同的。


引自doc

One thing to note when using routes with params is that when the user navigates from /user/foo to /user/bar, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. However, this also means that the lifecycle hooks of the component will not be called.

To react to params changes in the same component, you can simply watch the $route object


我应该发布问题吗?

感谢您的帮助!

最佳答案

你能检查这个工作示例吗:https://jsfiddle.net/mani04/dLnz4rbL/

我尝试使用 Transitioning Between Elements 中描述的方法在文档中。

在我的 fiddle 示例中,它主要使用您的问题描述中的代码,我在组件中使用了一个 transition 包装器,如下所示:

<transition name="fade" mode="out-in">
<div class="page-contents" :key="$route.params.id">
This is my chapter component. Page: {{parseInt($route.params.id)}}
</div>
</transition>

文档指定我们需要提供一个 key 来使它们成为 Vue.js 的不同元素。所以我添加了你的章节 ID 作为键。

我不知道这是一个 hack 还是一个合适的解决方案,我在 2 周前才从 Angular2 迁移到 Vue。但在有人为您提供更好的解决方案之前,您可以使用此方法来获取动态路由的转换。

关于在 vue-router 的 github 页面中将此作为问题发布,我不确定这是否符合解决/修复的条件,但您肯定会引起他们的注意。修复可能涉及不重用组件,这也不理想。所以这对他们来说是一个艰难的呼吁。但是讨论绝对应该很有趣!如果您决定创建一个,请在此处发回问题链接 :-)

关于javascript - 动态路由上的 Vue.js 2.0 转换未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com