我有一个应用程序包含在此div:
<div id="app" v-bind:style='{backgroundColor: backgroundColor}'>
... the app ...
</div>
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
我希望背景依赖于当前路线(router.currentRoute.path).
但是,上面的解决方案不起作用,因为router.currentRoute.pathVue实例未检测到已更改(不是被动).
从Vue实例中访问动态路由器数据的正确方法是什么?
tha*_*ksd 13
router创建的对象new VueRouter不是被动的,因为Vue无法知道观察和更新其范围之外的任何对象.
传递router的Vue配置对象是允许的电流路线观看,但你需要通过引用它this.$route:
if (this.$route.path == "/foo") {
...
}
Run Code Online (Sandbox Code Playgroud)
您也可以通过访问整个router对象this.$router,但其数据不是被动的.