index.vue 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <view @longtap.stop="longtap">
  3. <canvas
  4. :width="destWidth"
  5. :height="destHeight"
  6. :canvas-id="item.id"
  7. :id="item.id"
  8. :style="{width:width,height: height}"
  9. v-for="(item,index) in listCode"
  10. :key="item.id"
  11. @error="handleError"></canvas>
  12. </view>
  13. </template>
  14. <script>
  15. import { BarCode, GetCodeImg,GetPixelRatio,GetPx } from '../../js_sdk';
  16. import { getUUid, deepClone ,platform} from '../../common/helper.js'
  17. export default {
  18. name: 'WBarcode',
  19. props:{
  20. options:{
  21. type: Object,
  22. required: true,
  23. default: () =>{
  24. return {
  25. }
  26. }
  27. }
  28. },
  29. data () {
  30. return {
  31. destHeight: 0,
  32. destWidth: 0,
  33. width: 0,
  34. height: 0,
  35. listCode: [],
  36. id: getUUid()
  37. }
  38. },
  39. mounted() {
  40. this.height = GetPx(this.options.height) + 'px';
  41. this.width = GetPx(this.options.width) + 'px';
  42. this.destHeight = GetPx(this.options.height) * GetPixelRatio() + 'px';
  43. this.destWidth = GetPx(this.options.width) * GetPixelRatio() + 'px';
  44. this.SpecialTreatment(this.options)
  45. this.$nextTick(()=>{
  46. this.generateCode();
  47. })
  48. },
  49. watch: {
  50. options:{
  51. deep: true,
  52. handler (val) {
  53. this.height = GetPx(val.height) + 'px';
  54. this.width = GetPx(val.width) + 'px';
  55. this.destHeight = GetPx(this.options.height) * GetPixelRatio() + 'px';
  56. this.destWidth = GetPx(this.options.width) * GetPixelRatio() + 'px';
  57. this.SpecialTreatment(val)
  58. setTimeout(()=>{// h5平台动态改变canvas大小
  59. this.generateCode();
  60. },50)
  61. }
  62. }
  63. },
  64. methods: {
  65. longtap (e){
  66. this.$emit('press',e)
  67. },
  68. handleError (e) {//当发生错误时触发 error 事件,字节跳动小程序与飞书小程序不支持
  69. this.$emit('error',e.detail)
  70. },
  71. SpecialTreatment (val) {//微信小程序渲染多个canvas特殊处理
  72. let obj = deepClone(val);
  73. obj.id = this.id;
  74. this.listCode = [obj]
  75. },
  76. generateCode () {
  77. try{
  78. const parameter = {...this.options,source: platform(),id: this.id,ctx: this};
  79. BarCode(parameter,(res)=>{
  80. this.$emit('generate',res)
  81. })
  82. }catch(err){}
  83. },
  84. async GetCodeImg (){
  85. try{
  86. return await GetCodeImg({id: this.id,width: this.options.width,height: this.options.height,ctx: this});
  87. }catch(e){}
  88. }
  89. }
  90. }
  91. </script>