vue.js - 为什么 router.currentRoute.path 不是响应式(Reactive)的?

标签 vue.js vue-router

我有一个应用程序包含在这个 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 已更改(不是响应式(Reactive))。

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

最佳答案

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

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

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

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


如果您将 Vue 2 与组合 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)

关于vue.js - 为什么 router.currentRoute.path 不是响应式(Reactive)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45328370/

相关文章:

vue.js - Vuejs v-for 设置唯一数据

javascript - 在本地组件 vuejs 中访问 Prop 值

vue.js - 为什么我不能在我的 Vue 应用程序上使用调试器或 console.log

vue.js/Vue getter 未定义错误

vue.js - 访问任何子路线时如何在父路线链接上获得事件类(class)?

vuejs2 - 如何判断 Vue-Router 导航钩子(Hook)是否由 "push"触发?

vue.js - Vue-router:是否可以在通过路径以编程方式重定向时传递参数?

javascript - vue-router:浏览器尝试将 <router-link> 作为本地文件打开

javascript - Vue Router next 回调总是在 beforeEach 中调用

typescript - 如何在Vue和TypeScript应用程序中全局正确注册axios