uniapp vue3 canvasToTempFilePath:fail fail canvas is empty报错
问题:
- 使用uniapp+vue3开发微信小程序,生成海报无法保存,报错canvasToTempFilePath:fail fail canvas is empty?
解决:
- 如果你看了微信社区应该会知道其实就是没有传递this的问题,那我们使用了Vue3里setup语法糖是不存在this的
- 这个时候Vue的
getCurrentInstance闪量登场,getCurrentInstance就是来获取当前组件实例 - 记下来请看代码示例
示例
- 错误示例
// 写法一 (不传递this)
uni.canvasToTempFilePath({
// 画布的id
canvasId: 'canvas',
success(res) {
// ...
},
fail(reason) {
// ...
}
})
// 写法二 (传递了this,但是setup当中不存在this,所以也会报错)
uni.canvasToTempFilePath({
// 画布的id
canvasId: 'canvas',
success(res) {
// ...
},
fail(reason) {
// ...
}
}, this)
- 正确写法
// 导入
import { getCurrentInstance } from 'vue'
// 获得当前组件实例
const instance = getCurrentInstance()
// 调用保存
uni.canvasToTempFilePath({
// 画布的id
canvasId: 'canvas',
success(res) {
// ...
},
fail(reason) {
// ...
}
}, instance)