Vue 路由问题
Vue router issue
我在 vue 组件文件中有一个如下所示的 link。
<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
文件中的路由设置如下
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: MainBody
},
{ path: '/word/:id',
name: 'word',
component: Word
}
]
});
我得到 URL 如下所示
http://localhost:8080/word/4
我正在尝试捕捉 word.vue
中的 URL 参数,如下所示
<script>
export default {
watch: {
'$route': 'routeChanged'
},
methods: {
routeChanged () {
console.log(this.$route.params.id);
}
}
}
</script>
问题是当我单击 <li></li>
时,我没有在 console
中获得任何值,当我第二次单击时,我获得了值。
为什么会这样?我想第一次获得价值。
我建议你在 mounted() 和 updated() 中捕获值。
methods: {
getid: function()
{
this.wordid = this.$route.params.id
}
},
watch: {
wordid: function(val) {
console.log(this.wordid) // or console.log(val)
}
},
mounted()
{
this.getid()
},
updated()
{
this.getid()
}
您的问题是由于您正在观察变化造成的。为了更好地理解这个问题,这里有一个时间表:
- 用户点击“http://localhost:8080/word/4”
- Vue 路由器更新
$route
- 路由器视图更新视图,将
MainBody
换成 Word
,更新传递的属性并调用 created
和 mounted
从word
的角度来看,没有任何变化,它不调用watch
从任何方法手动解析 $route
都不是最干净的解决方案,更好的方法是将 props 与 watcher 结合使用来获取您的 id:
<script>
export default {
props: {
id: String,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
确保在您的路由器中指定 props: true
如果使用此:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},
我在 vue 组件文件中有一个如下所示的 link。
<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
文件中的路由设置如下
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: MainBody
},
{ path: '/word/:id',
name: 'word',
component: Word
}
]
});
我得到 URL 如下所示
http://localhost:8080/word/4
我正在尝试捕捉 word.vue
中的 URL 参数,如下所示
<script>
export default {
watch: {
'$route': 'routeChanged'
},
methods: {
routeChanged () {
console.log(this.$route.params.id);
}
}
}
</script>
问题是当我单击 <li></li>
时,我没有在 console
中获得任何值,当我第二次单击时,我获得了值。
为什么会这样?我想第一次获得价值。
我建议你在 mounted() 和 updated() 中捕获值。
methods: {
getid: function()
{
this.wordid = this.$route.params.id
}
},
watch: {
wordid: function(val) {
console.log(this.wordid) // or console.log(val)
}
},
mounted()
{
this.getid()
},
updated()
{
this.getid()
}
您的问题是由于您正在观察变化造成的。为了更好地理解这个问题,这里有一个时间表:
- 用户点击“http://localhost:8080/word/4”
- Vue 路由器更新
$route
- 路由器视图更新视图,将
MainBody
换成Word
,更新传递的属性并调用created
和mounted
从word
的角度来看,没有任何变化,它不调用watch
从任何方法手动解析 $route
都不是最干净的解决方案,更好的方法是将 props 与 watcher 结合使用来获取您的 id:
<script>
export default {
props: {
id: String,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
确保在您的路由器中指定 props: true
如果使用此:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},