[英]VUEJS vue-router access router from nested routes
I have problem to access route object from nested views. 我有从嵌套视图访问路由对象的问题。 Here is the simplified code:
这是简化的代码:
main.js 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 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>
It says "router is undefined", when I use 当我使用时,它说“路由器未定义”
this.$router.go(-1)
from main routes (aka /contacts), it works. 从主要路线(又名/ contacts)出发,就可以了。 I tried all of the below code on the child:
我对孩子尝试了以下所有代码:
router.go(-1)
$router.go(-1)
this.$router.go(-1)
this.router.go(-1)
this.$parent.$router.go(-1)
None of them works. 它们都不起作用。 Is there a way to reach to router object from nested routes?
有没有办法从嵌套路由到达路由器对象? Or should I emit an event to parent and change view from there?
还是应该向父母发送事件并从那里更改视图?
I have found an error in your code - it's in ()=>{...}
function :) 我在您的代码中发现错误-它在
()=>{...}
函数中:)
Using an arrow function you are addressing ContactDetails
-component this
(object) and it does not contain any $router
indeed. 使用箭头功能,您正在寻址
ContactDetails
this
(对象),它实际上不包含任何$router
。 After you change an arrow function to function() {}
your code will work as expected, because Vue rebinded to its instance where the $router
is declared. 将箭头函数更改为
function() {}
您的代码将按预期工作,因为Vue重新绑定到声明$router
实例。
Now, lets look at this working copy (codepen) of your code: 现在,让我们看一下代码的此工作副本(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.