问题描述
iView中例如表格Table的column中,一些属性是由render函数渲染的,有时候需要在render函数中,调用data里面的数据,就要用到this.someProperty,不过发现这个时候,this是空的(undefined)
解决方案
解决办法也比较简单,在data()里面,return前面指定一个变量存储下this,作为缓存来使用,示例如下:
data() { // 使用that存储下this实例,以便在column1的render函数下调用 var that = this; return { spinShow: false, educations:[], // 学历字典表 page1: {current: 1, total: 0, limit: 10}, columns1: [ {title: '姓名', key: "name", align: 'center', minWidth: 60, render: function (h, params) { return h('div', [ h('a', {style:{color: '#499AF2'}, domProps: { href: '/student?id='+params.row.student.id, target: '_blank' }}, params.row.student.name) ]); } }, {title: '学历', key: "education", align: 'center', minWidth: 70, render: function (h, params) { // 这里使用了that,that.educations就能正常取到了 var founded = that.educations.find(function (item) { return item.no === params.row.student.education; }); return h("span", founded?founded.name:'') } } ] } }
如果是非Vue模板应用程序,可以使用var app = new Vue(),然后在data里面的render函数使用app,如下:
var app = new Vue({ el: '#app', data: { spinShow: false, educations: [], // 学历字典表 page1: { current: 1, total: 0, limit: 10 }, columns1: [{ title: '姓名', key: "name", align: 'center', minWidth: 60, render: function(h, params) { return h('div', [h('a', { style: { color: '#499AF2' }, domProps: { href: '/student?id=' + params.row.student.id, target: '_blank' } }, params.row.student.name)]); } }, { title: '学历', key: "education", align: 'center', minWidth: 70, render: function(h, params) { // 这里使用了app,app.educations就能正常取到了 var founded = app.educations.find(function(item) { return item.no === params.row.student.education; }); return h("span", founded ? founded.name : '') } }] } })
文章评论