首页 > 解决方案 > Vue单文件组件中启用管道操作符的最简单方法

问题描述

在 Vue 单文件组件中启用管道运算符的最简单方法是<template>什么<script>

例子:

<template>
  <span>
    <!-- should display as −15,395.94 -->
    {{ amount |> currency }}
  </span>
</template>

<script>
  const currencyFormatter = new Intl.NumberFormat("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

  // though they look like the same symbol, they are not
  const HYPHEN_MINUS = "-";
  const MINUS_SIGN = "−";

  function hyphenToMinus(value) {
    return String(value).replace(HYPHEN_MINUS, MINUS_SIGN);
  }

  export default {
    data: _ => ({
      amount: -15395.94,
    }),
    methods: {
      currency: value => value
        |> currencyFormatter.format
        |> hyphenToMinus
      ,
    },
  };
</script>

注意:我想使用 Vue CLI,vue.config.js而不是直接使用 webpack 配置。

注意:我不想使用Vue 过滤器。有人谈论在未来版本的 Vue 中删除过滤器,我希望为这个功能尝试“标准”JS 语法。

关于 Babel 中的管道运算符:@babel/plugin-proposal-pipeline-operator

标签: javascriptwebpackvuejs2vue-componentbabeljs

解决方案


经过两天的研究,终于找到了 Vue 3 的答案。不过不知道它是否适用于 Vue 2。

要在单个文件组件的模板中启用babel 插件,您需要在loader的参数compilerOptions.expressionPlugins中指定它们。vue-loader

如果你使用 Vue CLI:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          expressionPlugins: [['pipelineOperator', { proposal: 'fsharp' }]],
        }
        return options
      })
  },
}

如果你使用 Webpack:

// webpack.config.json
module.exports = {
  // other options
  module: {
    rules: [
      // other rules
      {
        test: /\.vue$/,
        use: {
          loader: 'vue-loader',
          options: {
            compilerOptions: {
              expressionPlugins: [['pipelineOperator', { proposal: 'fsharp' }]],
            },
          },
        },
      },
    ]
  }
}

推荐阅读