uni-app x在template中调用methods中的函数,传入的数组中包含对象时,对象中属性丢失

发布于 1周前 作者 gougou168 来自 Uni-App

uni-app x在template中调用methods中的函数,传入的数组中包含对象时,对象中属性丢失

开发环境 版本号 项目创建方式
Windows Windows10 HBuilderX 4.01

示例代码:

<template>
<uni-shadow-root class="vant-weapp-button-index">
<button ref="van-button" :class="getClass('button', [type, size, { plain, round }])" :type="type">
<text v-if="text">{{text}}</text>
<slot v-else></slot>
</button>
</uni-shadow-root>
</template>  
<script lang="uts">
export default {
name: "van-button",
props: {
text: {
type: String,
default: ''
},
type: {
type: String,
default: 'default'
},
size: {
type: String,
default: 'normal'
},
plain: {
type: Boolean,
default: false
},
round: {
type: Boolean,
default: true
}
},
methods: {
getClass(name : string, conf : any[]) : string {
console.log(JSON.stringify(conf))
return name + JSON.stringify(conf)
},
}
}
</script>

操作步骤:

在template中调用methods中的getClass函数

预期结果:

拿到传入的所有值

实际结果:

数组中的对象属性丢失

bug描述:

函数getClass包含两个参数,第一个参数为string类型,第二个为any[],可以为[‘a’, {b:1},[‘c’]],在getClass中打印时发现,对象中的属性丢失


1 回复

uni-app x 中,如果你在 template 中调用 methods 中的函数,并传入一个包含对象的数组时,发现对象中的属性丢失,可能是由于以下几个原因导致的:

1. 数据绑定问题

  • 确保你在 template 中传递的数据是正确的,并且数据在 datacomputed 中已经正确定义。
  • 如果数据是通过异步请求获取的,确保在数据加载完成后再进行传递。

2. 函数参数传递问题

  • 确保你在 template 中调用函数时,传递的参数是正确的。如果参数是一个对象,确保对象中的属性已经被正确赋值。

3. 函数内部处理问题

  • 检查你在 methods 中定义的函数,确保函数内部正确处理了传入的参数。

4. 数据响应性问题

  • 如果你在 template 中传递的数据是响应式的,确保数据是响应式的,并且属性已经被正确监听。

示例代码

假设你在 template 中调用 methods 中的 handleArray 函数,并传入一个包含对象的数组:

<template>
  <view>
    <button @click="handleArray([{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }])">Click Me</button>
  </view>
</template>

<script>
export default {
  methods: {
    handleArray(arr) {
      arr.forEach(item => {
        console.log(item.name, item.age); // 确保这里能正确输出对象的属性
      });
    }
  }
}
</script>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!