5

如何在 Vue 的计算属性中传递参数

 3 years ago
source link: https://my.oschina.net/lav/blog/5085343
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在 Vue 中,计算属性(computed )是从其他响应式属性派生的属性,是用于自动监听响应式属性的变化,从而动态计算返回值。计算属性(computed )通常是一个没有参数的函数。当然如果需要像调用方法一样给计算属性传递参数也是可以的,本文介绍两种向计算属性传参的方法。

1.返回函数

这种方式通过计算属性返回的函数来进行传参,如下代码片段,对于一条未审核通过的记录,审核时间为 0,这是显示 --

<template>
    <div id="app">
        <p>
            <label>审核时间:</label>
            <i class="number">
                {{ auditTime(1624314956) }}
            </i>
        </p>
    </div>
</template>

<script>
export default {
  computed: {
    auditTime: () => {
        return (timestamp) => (timestamp > 0 ? convertDate(timestamp) : "--");
    },
  },
};
</script>

上面代码的计算属性 auditTime,返回一个箭头函数,接收参数timestamp为时间戳,函数 convertDate 实现了时间戳时间格式化。

2.filters

可以为组件添加一个过滤器 filters,以便可以在模板中按照想要的方式格式化值。

关于 vue 过滤器,在官方文档中定义如下:

Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化。过滤器可以用在两个地方:双花括号插值和 v-bind 表达式(后者从 2.1.0+ 开始支持)。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示。

<template>
    <div id="app">
        <p>
            <label>审核时间:</label>
            <i class="number">
                {{ 1624314956 | auditTime("--") }}
            </i>
        </p>
    </div>
</template>

<script>
export default {
    filters: {
        auditTime: (timestamp, defaultValue = "--") =>
            timestamp > 0 ? convertDate(timestamp) : defaultValue,
    },
};
</script>

在上面的片段中,当时间戳为0的时候输出的是 -- ,这个格式是否有种似曾相识的感觉,在《Angular管道PIPE介绍》中介绍的管道,方式类似。

 {{ 1621836603 | auditTime("--") }}

上面代码最终显示为:2021-06-22 06:35

 {{ 0 | auditTime("--") }}

上面代码最终显示为:--

关于计算属性中传参,当然可以在 methods 中定义相应的方法,两者主要区别是:computed 是可以被缓存的,methods 不能缓存。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK