Vue2—父组件通过 prop 传值给子组件,子组件值为空
1、问题2、方法13、方法2
1、问题
data数据初始化为空,由于ajax是异步的,加载子组件时,请求数据还没赋值,就会把data里面空的数据给传过去,所以子组件props接收到的值则为空。
2、方法1
子组件对父组件传递过来的值进行监听,如果val !== oldVal,则执行相应的逻辑。
export default {
props: ['powerstationId'],
watch: {
powerstationId (val, oldVal) {
if (val !== oldVal) {
this.getDeviceList()
}
}
},
}
3、方法2
首先利用v-if判断返回的数据不为空,当powerstationId不为空再传给子组件。
export default {
data () {
return {
activeName: 'first',
stationTitle: '',
powerList: [],
powerstationId: '',
}
},
methods: {
getPowerStation (id) {
powerstationOptions({}).then((res) => {
console.log('电站下拉框数据', res)
if (res.code === 200) {
this.powerList = res.result.optionList
if (id) {
let result = res.result.optionList.find(item => item.powerstationId === id)
this.powerstationId = result.powerstationId
this.stationTitle = result.powerstationName
} else {
this.powerstationId = res.result.optionList.length > 0 ? res.result.optionList[0].powerstationId : ''
this.stationTitle = res.result.optionList[0].powerstationName
}
}
})
}
}
}
|