我想使用TypeScript在Vue.js应用程序中检测我的URL中的更改。在JavaScript中,可以按以下步骤进行操作:
watch: {
'$route': {
handler: 'onUrlChange',
immediate: true,
deep: true
}
},
onUrlChange(newUrl){
// Some action
}
如何在TypeScript中做同样的事情?
答案 0 :(得分:8)
我在这里找到了解决方法:https://github.com/kaorun343/vue-property-decorator
可以这样做:
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: any) {
// Some action
}
答案 1 :(得分:4)
这就是我的方式
<script lang="ts">
import Vue from 'vue'
import { Route } from 'vue-router'
export default Vue.extend({
name: 'HelloWorld',
watch: {
'$route': {
handler: function(to: Route): void {
// Do something here.
console.log(to)
},
immediate: true,
},
},
})
</script>