vue template中使用可选链

110 阅读1分钟

在plugins文件夹下面创建文件 utils.js


export const optionalChaining = (obj, ...rest) => {
  let tmp = obj;

  for (let key in rest) {
    let name = rest[key];

    tmp = tmp?.[name];
  }

  return tmp || '';
};


在main.js中引入

import { optionalChaining } from './plugins/utils.js'; // 使template中可以使用可选链, 使用方法查看utils.js

// 挂载
Vue.prototype.$$ = optionalChaining;

用法示例

<template>
        // 即使没有值也不会报错
        <div>{{$$(user, 'a', 'b')}}</div>
        <div>{{$$(user, 'a', 'c')}}</div>
    </template>
    <script>
        export default{
            data() {
                return {
                    user: {
                        a: {
                            b:'ss',
                            c: '',
                        }
                    }
                }
            }
        }
    </script>