从嵌套视图访问路径对象时遇到问题。这是简化的代码:
main.js
import Vuetify from 'vuetify'
import VueRouter from 'vue-router'
import Vuetify from 'vuetify'
Vue.use(VueRouter)
Vue.use(Vuetify)
const router = new VueRouter({
routes : [
{path : '/contacts', component: Contacts,
children: [
{
path: ':id',
component: ContactDetails
}
]
},
],
mode: 'history'
})
new Vue({
el: '#app',
render: h => h(App),
router
})
ContactDetails.vue
<template>
<v-btn icon dark class="mr-3" @click.native="editContact">
<v-icon>edit</v-icon>
</v-btn>
</template>
<script>
export default {
data : () => ({
}),
methods: {
editContact: ()=>{
console.log('edit contact');
this.$router.go(-1) //this gives an error
}
},
}
</script>
当我使用
时,它表示&#34;路由器未定义&#34;this.$router.go(-1)
来自主要路线(又名/联系人),它的工作原理。我在孩子身上尝试了以下所有代码:
router.go(-1)
$router.go(-1)
this.$router.go(-1)
this.router.go(-1)
this.$parent.$router.go(-1)
它们都不起作用。有没有办法从嵌套路由到达路由器对象?或者我应该向父母发出一个事件并从那里更改视图?
答案 0 :(得分:0)
我在您的代码中发现错误-它在()=>{...}
函数中:)
使用箭头功能,您正在寻址ContactDetails
组件this
(对象),并且实际上不包含任何$router
。将箭头函数更改为function() {}
后,您的代码将按预期工作,因为Vue重新绑定到声明了$router
的实例。
现在,让我们看一下这段代码working copy (codepen):
Vue.use(VueRouter)
let ContactDetails = {
mounted() {
console.log('ContactDetails mounted...');
},
methods: {
editContact: function() {
console.log('edit contact');
this.$router.go(-1) //this DOES NOT give an error ANYMORE
}
},
template: `<button @click="editContact">edit</button>`,
}
let Contacts = {
components: {ContactDetails},
mounted() {
console.log('Contacts mounted...');
},
template: `Contacts... <ContactDetails></ContactDetails>`,
};
const router = new VueRouter({
mode: 'hash',
routes : [{
path : '/contacts',
component: Contacts,
children: [{
path: 'id',
component: ContactDetails
}]
}],
});
const vm = new Vue({
el: '#app',
components: {
Contacts,
ContactDetails,
},
router
});
vm.$router.push("/contacts/id");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<router-view></router-view>
</div>