Vue 中的 filter 带多参

场景

在 vue 项目中,团队成员在模板中解析一个 json 字符串,然后这个字符串来自于后台,所以是类型不安全,直接用 JSON.parse 就报错了,这里需要用 trycatch 下。

实际是,因为这个解析 json 字符串的方法是纯函数,且经常用在模板中,所以作为 filter 合适,直接拷贝了其他项目的这个方法过来作为 fitlers 用,如下。

// omit other properties
  filters: {
    tryParseJsonString(jsonStr, defaultValue) {
      let ret = defaultValue;
      if (jsonStr) {
        try {
          ret = JSON.parse(jsonStr) || defaultValue;
        } catch (e) {
          console.warn('JSON格式不正确,解析失败', e.message);
        }
      }

      return ret;
    }
  },
// ...

在模板中,可以绑定到 v-bind,使用如下

<template>
  <comp :images="li.value | tryParseJsonString([])" />
</template>

考虑到这个 filter 使用频繁,所以可以封装进全局 mixin,避免频繁的引用。

参考 https://vuejs.org/v2/guide/fi…

    原文作者:大暗扣
    原文地址: https://segmentfault.com/a/1190000019760356
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞