在 Vue3 中使用过滤器但无法读取 globalProperties [英] Use filter in Vue3 but can't read globalProperties

查看:87
本文介绍了在 Vue3 中使用过滤器但无法读取 globalProperties的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个简单的问题,

我知道 Vue3 不再使用过滤器,注释说使用计算或方法代替.但还有一个我们可以使用的 globalProperties,我使用了这个 globalProperties,但不断收到此错误

I know that Vue3 doesn't use filters anymore and notes says use computed or methd instead. but also there is a globalProperties we can use, I used this globalProperties but keep getting this error

未捕获的类型错误:无法读取未定义的属性globalProperties"

有谁知道我的代码中的错误在哪里?

Does anyone know where is the bug in my code?

const app = {
data() {
    return {
        message: ""
    }
  }
}

app.config.globalProperties.$filters = {
formatDate(value) {

    if (value == "0001-01-01T00:00:00")
        return "";
    var today = new Date(value);
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();

    today = dd + '/' + mm + '/' + yyyy;
    return today;
   }
}

Vue.createApp(app).mount('#app');

我正在像这样在我的表格中使用过滤器

And I am using the filter in my table like this

    <td>
         {{ $filters.formatDate(incident.incidentData) }}
    </td>

推荐答案

config 字段属于 root 实例 不属于 root 组件 所以你应该这样做:

The config field belongs to the root instance not to the root component so you should do:

const app = {
data() {
    return {
        message: ""
    }
  }
}
const myApp=Vue.createApp(app)

myApp.config.globalProperties.$filters = {
formatDate(value) {

    if (value == "0001-01-01T00:00:00")
        return "";
    var today = new Date(value);
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();

    today = dd + '/' + mm + '/' + yyyy;
    return today;
   }
}

myApp.mount('#app');

Vue.createApp(app) 返回根实例

Vue.createApp(app) return the root instance

myApp.mount('#app'); 将根应用挂载到元素后返回根组件

myApp.mount('#app'); after mounting root app to an element it returns the root component

这篇关于在 Vue3 中使用过滤器但无法读取 globalProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆