javascript - 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。
解决方案
经过两天的研究,终于找到了 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' }]],
},
},
},
},
]
}
}
推荐阅读
- octave - 多元曲线拟合实验数据
- javascript - 如何在Jquery中删除每个表TD和TR中的重复数据
- python - Python - 删除从 csv 读取的数据帧中的第一列 0
- powershell - 带时间戳的错误日志
- python-3.x - 在 macOS 中,如何在应用程序菜单中添加自定义菜单项?
- javascript - 使用 javascript 触发页面缩放事件
- python-3.x - 我想使用 python 从文本文件中读取部分文本
- google-bigquery - 为什么参数不能在 UDF 的 LIMIT 语句中使用?
- python - Python脚本 - 如何从命令行参数将密码作为变量传递
- python - groupby和apply时如何将列名作为参数传递