Javascript Vue发送参数值,声明要作为哪个参数发送
我在页面创建时调用了一个名为Javascript Vue发送参数值,声明要作为哪个参数发送,javascript,vue.js,Javascript,Vue.js,我在页面创建时调用了一个名为fetchReport 这很好,我还调用了另外两个函数来更改select元素,它们也可以工作,但我的问题是: 目前,如果我调用handleTypeSelect或handleLocationSelect,它们都会提交正确的值,但每次都会在fetchReport调用中作为itemType提交。我假设这是因为他们只发送一个参数值,这是第一个参数 handleLocationSelect() { this.fetchReport(undefined, itemL
fetchReport
这很好,我还调用了另外两个函数来更改select元素,它们也可以工作,但我的问题是:
目前,如果我调用handleTypeSelect或handleLocationSelect,它们都会提交正确的值,但每次都会在fetchReport
调用中作为itemType提交。我假设这是因为他们只发送一个参数值,这是第一个参数
handleLocationSelect() {
this.fetchReport(undefined, itemLocations.value);
}
如何修改此选项,以便handleTypeSelect
将值作为itemType
发送,而handleLocationSelect
将值作为locationID
发送
created() {
this.fetchReport();
},
methods: {
fetchReport(itemType = '3', locationID = '10', startDate = new Date().toISOString().substring(0,10), endDate = new Date().toISOString().substring(0,10)) {
axios.get('/report/assets/data', {params:{itemType: itemType, startDate: startDate, endDate: endDate, locationID: locationID}})
.then(response => {
// handle success
console.log(response.data)
this.rows = response.data
})
},
handleTypeSelect() {
this.fetchReport(itemTypes.value);
},
handleLocationSelect() {
this.fetchReport(itemLocations.value);
}
}
使用undefined传递第一个参数
handleLocationSelect() {
this.fetchReport(undefined, itemLocations.value);
}
你需要传递两个参数 用于获取值
未定义
,因为窗口中可能存在未定义的
handleLocationSelect() {
this.fetchReport(void, itemLocations.value);
}
重构fetchReport的参数: 不要采用一系列参数
(arg1、arg2、arg3)
,而是采用单个参数(arg)
此arg
参数将是一个对象,包括作为参数所需的所有属性。作为后续操作,请在函数中移动默认值
你的结果是:
fetchReport(myParams) {
const defaults = { itemType: '3', locationID: '10', .... }; // list all other defaults, same as previous arguments
const params = Object.assign(defaults, myParams);
axios.get('/report/assets/data', { params })
.then(response => {
// handle success
console.log(response.data)
this.rows = response.data
})
},
然后,当您需要调用fetchReport时:
fetchReport({itemType:'MyValue'})
fetchReport({locationID:'MyValue'})
当您不想考虑参数的顺序时,这是处理具有多个参数的函数的最佳实践方法。这不会弄乱我为taskType设置的默认值“3”,而是发送未定义的?@TomN。不会。将使用默认值3