[英]vue js component doesn't rerender on the same page
I have a component我有一个组件
<template>somecode</template>
<script>
export default {
name: 'Card',
created() {
axios.get(apiObjUrl)
somecode
})
}
</script>
this my url: http://127.0.0.1:8080/#/card/12这是我的网址:http: //127.0.0.1 :8080/#/card/12
But I have a problem:但我有一个问题:
when I use router-link like this:当我像这样使用路由器链接时:
<router-link to="/card/155"> card 155</router-link>
my url changes: http://127.0.0.1:8080/#/card/155我的网址更改:http: //127.0.0.1 :8080/#/card/155
but the created()
method doesn't get fired.但是
created()
方法不会被解雇。 so I don't make new xhr request to api and data not changes what do I do?所以我不会向 api 提出新的 xhr 请求,并且数据不会改变我该怎么办?
As an alternative you can setup a key attribute on your <router-view>
like this:作为替代方案,您可以像这样在
<router-view>
上设置关键属性:
<router-view :key="$route.fullPath"></router-view>
As <router-view>
is a component itself and unique keys force replacement of component instead of reusing it.由于
<router-view>
本身就是一个组件,并且唯一键强制替换组件而不是重用它。 So you can make use of life cycle hooks.所以你可以利用生命周期钩子。
That's just because your component is already created.那只是因为您的组件已经创建。 You may try using the lifecycle hook
updated()
instead of created()
.您可以尝试使用生命周期钩子
updated()
而不是created()
。
export default {
name: 'Card',
updated() {
axios.get(apiObjUrl)
somecode
})
}
Note: This will only work if your DOM changes.注意:这仅在您的 DOM 更改时才有效。 If you just want to listen on url changes and update accordingly you better
$watch
your route like this.如果您只想收听 url 更改并相应地更新,您最好像这样
$watch
您的路线。
export default {
name: 'Card',
created() {
axios.get(apiObjUrl)
somecode
}),
watch: {
'$route': function() {
// do your stuff here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.