全局属性在模板使用时报错

140 阅读1分钟

有关在定义在app.config.globalProperties里的属性在模板上使用报错问题

全局属性使用报错.png

解决方法

  1. 找到文件shims-vue.d.ts 或者新建一个.ts或".d.ts"文件
    export {}
 
    declare module 'vue' {
      interface ComponentCustomProperties {
        $filters: any
      }
    }
    
    // 以下这段代码也可以生效 确定类型
    // export {}

    // declare module '@vue/runtime-core' {
    //   interface ComponentCustomProperties {
    //     $filter: {
    //       name: string
    //       formatTime: (value: string) => string
    //       // 添加其他属性和方法的类型声明,如果有的话
    //     }
    //   }
    // }
  1. 使用this.$filter 在模板中,尝试使用this.$filter而不是$filter来访问全局属性。这有助于Vue类型系统正确识别全局属性,因为它知道this是一个Vue组件实例。
<div class="create-time">
  {{ this.$filter.formatTime(data?.row[data.item.prop]) }}
</div>