vue js v-link 同路由不更新内容

Vue js v-link same route does not update content

如果我在路线上:

person/:slug

然后我点击 link:

<div v-for="person in persons" v-link="{ name: 'person', params: { slug: person.slug }}">

URL会改变参数但实际的content/component不会更新。如果我点击刷新,它会因为 URL 已更新。我试过 canReuse 属性 没有任何运气。

路线:

router.map({
    '/': {
        name: 'search',
        component: Search
    },
    '/person/:slug': {
        name: 'person',
        component: Person
    }
})

组件:

<template>
    {{ person.slug }}
</template>


<script>
    import PersonRepository from '../person-repository.vue'

    export default {
        data () {
            return { person: null }
        },
        asyncData (resolve, reject) {
            return PersonRepository.get(this, this.$route.params.slug).then((person) => {
                return { person: person }
            })
        }
    }
</script>

您是否尝试过使用路由器挂钩而不是异步数据?现在推荐的方式是路由器挂钩。

您特别需要数据挂钩:http://vuejs.github.io/vue-router/en/pipeline/data.html

Called on an incoming component during the activation phase, after the activate hook has been resolved. It is also called when the route has changed and the current component is reused. Use this hook to load and set data on the current component.

export default {
    data () {
        return { person: null }
    },
    route:{ 
        data: function (transition) {
            return PersonRepository.get(this, this.$route.params.slug).then((person) => {
                return { person: person }
            })
        }
    }
}

通过返回承诺,您的组件将在承诺得到解决时重新加载。此外,您还可以访问 属性 $loadingRouteData,您可以使用它来显示加载微调器或其他内容。

观察路线变化并获取数据

对于版本 3+ 的 vue-router,您可以使用观察者并观察 $route 然后相应地更新您的数据:

export default {
    data () {
        return { person: null }
    },

    watch: {
       // call the method if the route changes
       '$route': {
         handler: 'asyncData',
         immediate: true // runs immediately with mount() instead of calling method on mount hook
       }
    },

    methods: {
       asyncData () {
           // ... your person fetching code
       }
    }
}

您可以在路线改变之后或之前获取。请参阅 the docs

试试这个:

<router-view :key="$route.fullPath"></router-view>