折腾:
【未解决】js中随机生成0或1
期间,写了代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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) } } |
结果运行报错
1 2 3 4 5 | 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) |
![](https://www.crifan.com/files/pic/uploads/2021/03/5732fc8f5cf042a89fa110f5d0557561.jpg)
vuejs is not a function
vuejs methods is not a function
把self改为this
1 2 3 4 5 6 7 8 9 | getRandom01() { return this .getRandomIntInclusive(0, 1) }, updateSwitchStatus() { const curRandom = this .getRandom01() console.log( 'updateSwitch: ' , curRandom) } |
就可以了:
![](https://www.crifan.com/files/pic/uploads/2021/03/2add1a8b727e45f89a869f4fa1ce2fae.jpg)
【总结】
vuejs的methods中调用其他函数,用了self.otherFunction,结果报错:
self.xxx is not a function
原因:
js中的对象本身是this,不是self。。。
看来是写其他语言用self多了,突然转js,都忘了是this了。。。。
转载请注明:在路上 » 【已解决】vuejs在methods调用别的函数报错:self.xxx is not a function