Vue can use this method when introducing external js files

When using the table component of iview, you need to import the column.js file from the outside. I found that this cannot be used in external files. I referred to online articles and wrote the following method:

1. First add an internal variable and a function to the external js file:

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. Then import this external js file into your vue page and pass in this

page.view

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)
	}
}

After passing in this step, this can be used in external files.

Guess you like

Origin blog.csdn.net/xjtarzan/article/details/128054998