我有一个应用程序包含在这个 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/