Ash*_*h K 5 typescript vue.js vuejs3
我正在Udemy 上学习本课程,但其内容已过时,因此我无法遵循作者创建全局过滤器的相同步骤。
而且从 Vue 3 文档看来,不再支持过滤器。
我在这里尝试做的事情相当简单,它只需要将价格作为数字并将其作为字符串美元价格返回,例如: take100和 return $100。
这对我不起作用。我的main.ts看起来像这样:
import { createApp } from "vue";
import { Vue } from 'vue-class-component';
import { viewDepthKey } from "vue-router";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.filter('price', function(input: number){
if(isNaN(input)){
return "-";
}
return '$' + input.toFixed(2);
})
createApp(App)
.use(store)
.use(router)
.mount("#app1");
Run Code Online (Sandbox Code Playgroud)
这是错误:
src/main.ts:8:5
TS2339: Property 'filter' does not exist on type 'VueConstructor<Vue<unknown, {}, {}>>'.
6 | import store from "./store";
7 |
> 8 | Vue.filter('price', function(input: number){
| ^^^^^^
9 | if(isNaN(input)){
10 | return "-";
11 | }
Run Code Online (Sandbox Code Playgroud)
这就是我尝试在模板中使用它的方式:
{{ item.product.price | price }}
Run Code Online (Sandbox Code Playgroud)
有没有办法让它工作或者我应该使用一些computed property?
编辑后续问题:
我的班级是这样的:
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { IProductInventory } from "@/types/Product";
import format from "@/helpers/format";
@Options({
name: "Inventory",
components: {}
})
export default class Inventory extends Vue{
inventory:IProductInventory[] = //Coming from an api call
}
</script>
Run Code Online (Sandbox Code Playgroud)
谢谢你!
Kei*_*las 11
在./helpers/filters.ts
const filters = {
price(input: number) {
if (isNaN(input)) {
return "-";
}
return '$' + input.toFixed(2);
}
}
export default filters;
Run Code Online (Sandbox Code Playgroud)
在您创建应用程序的地方全局安装它...
import filters from './helpers/filters'
const app = createApp(App);
app.config.globalProperties.$filters = filters
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)
然后就做
{{ $filters.price( price ) }}
Run Code Online (Sandbox Code Playgroud)
Vue 3 中删除了 filter 选项,因此您可以使用返回带有参数的函数的计算属性:
get formatPrice(): string{
return (price)=>{
if(isNaN(input)){
return "-"
}else{
//return other value
}
}
}
Run Code Online (Sandbox Code Playgroud)
而不是{{ item.product.price | price }}你会:
{{ formatPrice(item.product.price) }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7607 次 |
| 最近记录: |