问题描述:
在父组件data中定一个变量a:1,将a通过props传递到子组件中,并且定义a的类型为Number,默认值为1,当在父组件中改变a的值为underfind、null后,子组件中的使用的a并没有变动,watch、computed监听都失去活性。
问题原因:
在vue2与源码中对与标准的props的类型并且赋予默认值是对基础类型underfind、null默认进行了强校验,所以当给变量赋值underfind、null后,在子组件中对应的变量失去活性
解决方法(4种):
1.标准化父组件对应变量赋值,避免underfind、null出现
2.子组件使用数组方式定义props
3.子组件使用对象方式定义props时候可以移除赋予默认值的default参数,避免类型强校验
4.使用validator来定义变量的接受接收规则,underfind、null默认通过
父组件
<template>
<test :isSub="siteObj"/>
</template>
<script>
import test from "./test.vue"
export default {
name: 'Result',
data() {
return {}
},
mounted(){
this.init()
},
methods: {
async init() {
const that = this
setTimeout(function(){
that.siteObj = underfind
},2000)
},
}
}
</script>
子组件
<template>
<div>
11111111333{{ isSub }}+{{ isSubT }}
</div>
</template>
<script>
export default{
data:function(){
return {}
},
props:{
isSub:Number
},
// props:['isSub'],
// props:{
// isSub:Number,
// validator: function (value) {
// if(value==null) return true
// return value
// }
//},
computed:{
isSubT(){
return this.isSub
}
},
watch: {
isSub: function(val) {
}
},
}
</script>