vue在引入外部js文件时可以使用this的方法

在使用iview的table组件时,需要从外部引入column.js文件,发现在外部文件种无法使用 this,参考了一下网上的文章,写了以下方法:

1、首先在外部js文件中加入一个内部变量和一个函数:

columns.js

let _this = null
export default {
    
    
	// 接收从外部传入的this,并赋给_this
	receive(vm) {
    
    
        _this = vm
    },
    // column是表格列对象
    columns: [{
    
    
    	title: '姓名',
    	key: 'name',
    	render: (h, params) => {
    
    
    		return h('Button', {
    
    
    			on: {
    
    
    				click: () => {
    
    _this.showName(params.row)}
    			}
    		}, '按钮')
    	}
    }]
}

2、然后在你的vue页面中导入这个外部js文件,并传入this

page.vue

import columns from './columns.js'
export default {
    
    
	data() {
    
    
		tableColumns = columns.columns
	},
	methods: {
    
    
		// 外部js文件中可以调用这个方法_this.showName
		showName(value) {
    
    
			console.log(value.name)
		}
	},
	created() {
    
    
		// 把this传入这个外部文件里的receive方法中
		columns.receive(this)
	}
}

经过传入this这一步后,外部文件中就可以使用this了

猜你喜欢

转载自blog.csdn.net/xjtarzan/article/details/128054998