走在开发的路上
走在开发的路上
  • 发布:2020-03-13 15:17
  • 更新:2020-03-13 15:30
  • 阅读:1104

【报Bug】 template中使用methods方法参数变量复杂报错!

分类:uni-app

在<template>中使用
{{formatPopulation(data.population[index])}}
运行 -> 运行到小程序模拟器 -> 微信开发者工具

报错:
VM23562:1 [Vue warn]: Property or method "index" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

使用{{formatPopulation(data.population[0])}} 运行正常

结论:
在template中调用方法传入的参数包含方括号,并且方括号中是变量的话,作用域丢失从而指向实例属性。
若实例属性为定义则报错。

重现步骤

[步骤]

  1. 新建一个uni-app项目
  2. 新建页面,并输入如下代码
<template>  
    <div>  
        <div class="city" v-for="(item, index) in data.city">  
            <text>{{item.name}}: {{formatPopulation(data.population[index])}}万人</text>  
        </div>  
    </div>  
</template>

javascript

export default{  
        name: "ceshi",  
        data () {  
            return {  
                data: {  
                    city: [  
                        {name: "北京"},  
                        {name: "上海"},  
                        {name: "深圳"}  
                    ],  
                    population: [  
                        21540000, 24240000, 13026600  
                    ]  
                }  
            }  
        },  
        methods: {  
            formatPopulation(population) {  
                return population / 10000  
            }  
        }  
    }

3.运行 -> 运行到小程序模拟器 -> 微信开发者工具

IDE运行环境说明

HBuilder X 2.6.1.20200226

[mac版本号]

macOS 10.13.4 (17E199)

uni-app运行环境说明

[运行端是h5或app或某个小程序?]
微信小程序

[运行端版本号]

微信开发者工具 RC v1.02.1911181

联系方式

17601251932

2020-03-13 15:17 负责人:无 分享
已邀请:
wenju

wenju - https://www.mescroll.com -- 精致的下拉刷新和上拉加载组件

改成 formatPopulation(index) 试试

formatPopulation(index){  
  return this.data.population[index] / 10000    
}  
  • 走在开发的路上 (作者)

    您上述做法是可行的,谢谢抽出时间解答 0.0

    不过本题代码只是用来复现bug的例子

    我在目前的项目中也采用类似的兼容写法,不过这种方法的缺点是:函数功能不变,接收参数变量改变,那么就要再写一个方法来兼容参数的改变。

    所以我来这里提问,想请教大家是否碰到过我的问题,能不能更优雅的解决。

    或者官方团队能否修复这个问题。

    2020-03-13 16:58

该问题目前已经被锁定, 无法添加新回复