Vue路由器问题 [英] Vue router issue
问题描述
我在 vue 组件文件中有一个如下所示的链接.
I have a link like below in a vue component file.
<li v-for="(word,index) in allWord" v-bind:key="index">
<router-link :to="{ name: 'word', params: {id: word.id } }">
{{word}}
</router-link>
</li>
我在 index.js
文件中的路由设置如下
My route settings in index.js
file is like below
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: MainBody
},
{ path: '/word/:id',
name: 'word',
component: Word
}
]
});
我得到的网址如下
http://localhost:8080/word/4
我试图在 word.vue
中捕获 URL 参数如下
I am trying to catch URL parameter in word.vue
is like below
<script>
export default {
watch: {
'$route': 'routeChanged'
},
methods: {
routeChanged () {
console.log(this.$route.params.id);
}
}
}
</script>
问题是当我点击 <li></li>
我没有在 console
中获得任何价值,我在点击时获得价值第二次.
The issue is when I click on the <li></li>
I am not getting any value in console
, I am getting value when I click second time.
为什么会这样?我想第一次获得价值.
Why it is happening ? I would like to get value first time.
推荐答案
您的问题是由于您正在观察变化而引起的.为了更好地理解这个问题,以下是一个时间表:
Your issue is caused by that fact that you are watching changes. To better understand this issue, here is a timeline:
- 用户点击http://localhost:8080/word/4"
- Vue 路由器更新
$route
- Router 视图更新视图,将
MainBody
替换为Word
,更新传递的 props 并调用created
和mounted代码>
- User clicks "http://localhost:8080/word/4"
- Vue router updates
$route
- Router view updates the view, swapping out
MainBody
forWord
, updates the props passed and callscreated
andmounted
由于从word
的角度来看,没有任何变化,它不调用手表
Since from the view of word
, nothing has changed, it doesn't calls the watch
从任何方法手动解析 $route
都不是最干净的解决方案,更好的方法是结合使用 props 和 watcher 来获取您的 id:
Manually parsing $route
from any method isn't the cleanest solution, better is just to use the props in combination with the watcher to get your id:
<script>
export default {
props: {
id: String,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
如果使用这个,请确保在路由器中指定 props: true
:
Make sure to specify props: true
in your router if using this:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},
这篇关于Vue路由器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!