折腾:
【未解决】js中随机生成0或1
期间,写了代码:
methods: { ... getRandomIntInclusive(min, max) { // 返回随机值 含最大值,含最小值 min = Math.ceil(min) max = Math.floor(max) console.log('min=%s, max=%s', min, max) const randomValue = Math.floor(Math.random() * (max - min + 1)) + min console.log('randomValue=%s', randomValue) return randomValue }, getRandom01() { return self.getRandomIntInclusive(0, 1) }, updateSwitchStatus() { const curRandom = self.getRandom01() console.log('updateSwitch: ', curRandom) } }
结果运行报错
index.vue?c189:128 Uncaught TypeError: self.getRandom01 is not a function at VueComponent.updateSwitchStatus (index.vue?c189:128) updateSwitchStatus @ index.vue?c189:128....hot-update.js:1 07:58:56.371 index.vue?c189:143 Uncaught TypeError: self.getRandom01 is not a function at VueComponent.updateSwitchStatus (index.vue?c189:143)
vuejs is not a function
vuejs methods is not a function
把self改为this
getRandom01() { return this.getRandomIntInclusive(0, 1) }, updateSwitchStatus() { const curRandom = this.getRandom01() console.log('updateSwitch: ', curRandom) }
就可以了:
【总结】
vuejs的methods中调用其他函数,用了self.otherFunction,结果报错:
self.xxx is not a function
原因:
js中的对象本身是this,不是self。。。
看来是写其他语言用self多了,突然转js,都忘了是this了。。。。
转载请注明:在路上 » 【已解决】vuejs在methods调用别的函数报错:self.xxx is not a function