【问题标题】:Why isn't router.currentRoute.path reactive?为什么 router.currentRoute.path 没有反应?
【发布时间】:2018-01-01 20:38:15
【问题描述】:

我有一个包含在这个div 中的应用程序:

<div id="app" v-bind:style='{backgroundColor: backgroundColor}'>
  ... the app ...
</div>

路由是按照example in the documentation完成的(这是一个webpack项目):

import Vue from 'vue/dist/vue.js'
import VueRouter from 'vue-router'
import ComponentOne from './component1.vue'
import ComponentTwo from './component2.vue'

Vue.use(VueRouter)

const routes = [{
        path: '/foo',
        component: ComponentOne
    },
    {
        path: '/bar',
        component: ComponentTwo
    }
]

const router = new VueRouter({
    routes // short for `routes: routes`
})

const app = new Vue({
    router,
    data: {
        day: "Monday"
    },
    computed: {
        backgroundColor: function () {
            console.log(JSON.stringify(router.currentRoute))
            if (router.currentRoute.path == "/foo") {
                return "green"
            } else {
                return "blue"
            }
        }
    }
}).$mount('#app')

我希望背景依赖于当前路线 (router.currentRoute.path)。

但是,上面的解决方案不起作用,因为 Vue 实例未检测到 router.currentRoute.path 已更改(不是响应式的)。

从 Vue 实例中访问动态路由器数据的正确方法是什么?

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    通过 new VueRouter 创建的 router 对象不是响应式的,因为 Vue 无法知道监视和更新其范围之外的任何对象。

    Vue 配置对象中传递router 是允许监视当前路线的原因,但您需要通过this.$route 引用它:

    if (this.$route.path == "/foo") {
      ...
    }
    

    您也可以通过this.$router 访问整个router 对象,但它的数据不是反应式的。


    如果您使用 Vue 2 和 composition api setup() 方法,您可以这样做:

        import { computed } from '@vue/composition-api'
        export default {
          setup (props, context) {
            const params = computed ( () => context.root.$route.params)
            const path = computed( () => context.root.$route.path)
    

    【讨论】:

    • 我刚刚测试过(在console.log()if条件下都替换了routerby this.$router),行为是一样的:router.currentRoute.path在初始设置后没有更新在路线改变时。我将查看文档以了解 $router 表示法。
    • 谢谢。我刚刚输入了关于 this.$route 工作正常的评论(并使用文档链接更新了您的答案)
    • 很酷,我没有意识到 this.$router 对象根本没有被观看。很高兴知道!
    • 不过,我想知道为什么this.$route.path 可以,而this.$router.currentRoute 不行。我原以为$route 是从$router 派生的。
    • 我不知道内部逻辑,但我假设 VueRouter 插件中的代码专门使当前的 $route 反应但不会使整个 $router 对象反应跨度>
    【解决方案2】:

    我在 Vue 的 documentation 页面上找到了使用 watch 来跟踪路由器的过渡动画。不确定这是否是最佳实践,但您可以使用 to.path 或 from.path 来获取路径。

    // then, in the parent component,
    // watch the `$route` to determine the transition to use
    watch: {
      '$route' (to, from) {
        const toDepth = to.path.split('/').length
        const fromDepth = from.path.split('/').length
        this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多