Select中获取name的几种方式
// 方式一:初始化时构造 { id: name } 映射结构,便于保存时根据id直接获取name值
const idNameMap = {}
function init() {
axios('/api/getSelectOptions').then((res) => {
const selectOptions = res.data || []
const options = []
selectOptions.forEach((item) => {
// 构造 option
options.push(`<option value="${item.id}">${item.name}</option>`)
// 构造 { id: name } 映射
idNameMap[item.id] = item.name
})
this.state.options = options
})
}
function submit(formValue) {
const params = Object.assign({}, formValue)
const { name } = formValue
params.name = name
params.id = idNameMap[name]
axios('/api/submit', params)
}
// 方式二:根据 id 在初始select options 列表里找 name
let selectOptions = []
function init() {
axios('/api/getSelectOptions').then((res) => {
selectOptions = res.data || []
// 构造 option
this.state.options = selectOptions.reduce((arr, next) => {
arr.push(`<option value="${next.id}">${next.name}</option>`)
}, [])
})
}
function submit(formValue) {
const params = Object.assign({}, formValue)
// 根据 id 在初始 selectOptions 列表里找 name
const target = selectOptions.find((item) => item.id == formValue.id)
target && (params.name = target.name)
axios('/api/submit', params)
}