<\/script>')

Why isn't router.currentRoute.path not responsive?

I have an application that contains this div

:

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

      

Routing is done in the following example in the documentation (this is a webpack project):

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')

      

I wanted the background to depend on the current route ( router.currentRoute.path

).

But the solution above does not work because it is router.currentRoute.path

not detected by the Vue instance as modified (not responsive).

What is the correct way to access dynamic router data from a Vue instance?

+3


source to share


1 answer


An object router

created with new VueRouter

is unresponsive because Vue has no way of knowing to observe and update any object outside of its scope.

Passing router

to a config object Vue

is what keeps track of the current route, but you need to refer to it via this.$route

:

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

      




You can also access the entire object router

through this.$router

, but its data is unresponsive.

+4


source







All Articles