前言
在写项目的时候忽然有了一个需求,就是通过响应的参数,去作为属性名调用其他对象的方法,或者属性。
Python
这样的话,就想到了Python的 getattr 函数
1
| getattr(object, name[, default])
|
JS
那JS里面有没有方法做的相同的效果呢?
因为并没有系统的学习过JS, 基本上需要什么功能就是看文档
尝试一
1 2 3 4 5 6 7 8 9 10 11 12
| # 定义了一个本地的对象,分 1 2 3 4 的属性,分别对应值 status: { 1: { type: '', msg: '未执行' }, 2: { type: 'info', msg: '正在执行' }, 3: { type: 'success', msg: '执行成功' }, 4: { type: 'danger', msg: '执行失败' } }
<!-- 通过scope的变量,来调用status对象的值,从而生成不同的按钮 --> <template slot-scope="scope"> <el-tag :type="status`${scope.row.status}`.type"> {{ status`${scope.row.status}`.msg }} </el-tag> </template>
|
上面的写法会直接报错,后面重新看了下文档,发现对象的方法和属性可以通过[]进行调用.
正确写法
所以,正确写法应该是这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| # 定义了一个本地的对象,分 1 2 3 4 的属性,分别对应值 status: { 1: { type: '', msg: '未执行' }, 2: { type: 'info', msg: '正在执行' }, 3: { type: 'success', msg: '执行成功' }, 4: { type: 'danger', msg: '执行失败' } }
<!-- 通过scope的变量,来调用status对象的值,从而生成不同的按钮 --> <template slot-scope="scope"> <el-tag :type="status[scope.row.status].type"> {{ status[scope.row.status].msg }} </el-tag> </template>
|
感觉遇到这种情况还是蛮多的,所以记录一下~