问题描述
Property 'activeName' does not exist on type 'Vue'
问题出现的环境背景及自己尝试过哪些方法
vue-property-decorator
在beforeRouteEnter中给属性初始化时,提示Property 'activeName' does not exist on type 'Vue'
相关代码
<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
@Component({
components: {},
beforeRouteEnter(to:any, from: any, next){
next(vm => {
console.log('vm-->', vm) //打印vm中存在activeName这个属性
vm.activeName = 'date'
// 此处提示:Property 'activeName' does not exist on type 'Vue'
})
}
})
export default class Demo extends Vue {
activeName:string = 'date'
}
</script>
你期待的结果是什么?实际看到的错误信息又是什么?
1、在beforeRouteEnter中打印 vm这个对象,是存在 activeName这个属性的
2、但是在使用 vm.activeName = 'date' 进行初始化时,提示:Property 'activeName' does not exist on type 'Vue'
尝试过的方法:
在my-property.d.ts文件中,将需要初始化的属性进行全局注册。但是这个方法,如果我很多文件需要使用不同的属性,那我就需要在这个文件中,每次需要使用到哪个属性,都进行全局注册一次,显得麻烦。各位大神有没有其他的解决办法?
// 1. 确保在声明补充的类型之前导入 'vue'
import Vue from 'vue'
// 2. 定制一个文件,设置你想要补充的类型
// 在 types/vue.d.ts 里 Vue 有构造函数类型
declare module 'vue/types/vue' {
// 3. 声明为 Vue 补充的东西
interface Vue {
$msg: Function,
$bus:Vue,
activeName: string
}
}
楼主,你好~
这里贴下我的解决方案: