vue-cli4+中配置可选链操作符兼容

转载链接:https://www.cnblogs.com/zhangrenjie/p/15015684.html
延申阅读:可选链操作符空值运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 安装依赖  npm install  @babel/plugin-proposal-optional-chaining -S
// @babel/plugin-proposal-nullish-coalescing-operator -S
// 在babel.config.js中 的 plugins中添加 "@babel/plugin-proposal-optional-chaining"

module.exports = {
plugins: [
'@babel/plugin-proposal-optional-chaining', //可选链 ?.
'@babel/plugin-proposal-nullish-coalescing-operator' //空值合并 ??
]
}

// template中使用
// 插件开发
export default {
install (Vue) {
const optionalChaining = (obj, ...rest) => {
let temp = obj
for(const key in rest) {
temp = temp?.[rest[key]]
}
return temp
}
vue.prototype.$chaining= optionalChaining
}
}


// main.js
import Vue from 'vue'
import Chaining from 'chaining'

Vue.use(Chaining)

// *.vue
<template>
<div>{{$$(obj, 'first', 'second') }}</div>
</template>