uni-app 组件通过v-bind方式向props传递属性值 取不到传入的属性值 只能取到默认值【get width: ƒ reactiveGetter() 】

uni-app 组件通过v-bind方式向props传递属性值 取不到传入的属性值 只能取到默认值【get width: ƒ reactiveGetter() 】

开发环境 版本号 项目创建方式
Mac 10.15 HBuilderX
产品分类:uniapp/H5

浏览器平台:Chrome
浏览器版本:*

组件通过props传递名为width的参数, 取不到传入的值, 不管传入什么数值, 都变成上层组件设置的默认750;
应该是组件 get width: ƒ reactiveGetter() 里有什么特殊操作的原因。
通过v-bind方式绑的参数在多层传递属性值时好像都有类似问题, 直接输出整个$props是有看到正确的属性值, 但是直接访问取到的是另一个值。

通过控制台输出:
console.log([this.$props, this.$props.width]);
-》
(2) [{…}, 750]
0:
backgroundColor: "#ffffff"
direction: "to right"
height: 100
path: "#FF511F,#FF8B49,#FF511F"
type: "linear-gradient"
width: 480
get backgroundColor: ƒ reactiveGetter()
set backgroundColor: ƒ reactiveSetter(newVal)
get direction: ƒ reactiveGetter()
set direction: ƒ reactiveSetter(newVal)
get height: ƒ reactiveGetter()
set height: ƒ reactiveSetter(newVal)
get path: ƒ reactiveGetter()
set path: ƒ reactiveSetter(newVal)
get type: ƒ reactiveGetter()
set type: ƒ reactiveSetter(newVal)
get width: ƒ reactiveGetter()
set width: ƒ reactiveSetter(newVal)
proto: Object
1: 750
length: 2

更多关于uni-app 组件通过v-bind方式向props传递属性值 取不到传入的属性值 只能取到默认值【get width: ƒ reactiveGetter() 】的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

Sorry, 这个问题不是bug, 是我对VUE不熟悉的原因, 把多层组件间props重组的逻辑放到了mounted事件里, 但是mounted事件的顺序是从内到外, 里层的子组件会先执行, 外层的组件mounted事件响应会后执行。 要把props重组传递的逻辑放到created 事件, created 事件的执行顺序跟mounted事件的顺序相反, 是从外向内的顺序执行。 把mounted改为created后, props的value和setter的值就一致了。

更多关于uni-app 组件通过v-bind方式向props传递属性值 取不到传入的属性值 只能取到默认值【get width: ƒ reactiveGetter() 】的实战教程也可以访问 https://www.itying.com/category-93-b0.html


这是一个典型的props响应式数据访问问题。在uni-app/Vue中,props传递的数据会被自动转换为响应式对象,直接访问时需要通过正确的姿势获取值。

问题原因分析:

  1. 你看到get width: ƒ reactiveGetter()说明props.width已被转为响应式属性
  2. 直接访问this.width会触发getter,可能返回了默认值
  3. 但$props对象中确实存储了正确的值480

解决方案:

  1. 在组件中正确访问props值:
// 方式1:使用计算属性
computed: {
  actualWidth() {
    return this.width
  }
}

// 方式2:在mounted中获取
mounted() {
  console.log(this.$props.width) // 正确值
}
  1. 检查父组件传值方式是否正确:
<!-- 确保使用v-bind传递数值而非字符串 -->
<child-component :width="480" />
  1. 如果是多层组件传递,确保中间组件正确透传props:
// 中间组件需要显式声明props
props: ['width']
回到顶部