<template>
|
<view class="bluetooth-printer">
|
<button @click="connectPrinter">连接蓝牙打印机</button>
|
<button @click="printTest">打印测试页</button>
|
<text>{{ connectionStatus }}</text>
|
</view>
|
</template>
|
|
<script>
|
export default {
|
props: ['printCmd'], // 从父组件传入的打印命令
|
data() {
|
return {
|
bluetoothSocket: null,
|
connectionStatus: '未连接'
|
};
|
},
|
methods: {
|
initBluetooth() {
|
try {
|
this.bluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");
|
plus.ui.toast("初始化蓝牙成功");
|
} catch (e) {
|
plus.ui.toast("初始化蓝牙失败:" + e);
|
}
|
},
|
connectPrinter() {
|
try {
|
if (this.bluetoothSocket && !this.bluetoothSocket.isConnected()) {
|
this.bluetoothSocket.connect();
|
this.connectionStatus = "蓝牙打印机已连接";
|
plus.ui.toast("打印机连接成功");
|
} else {
|
this.connectionStatus = "打印机已连接或连接中";
|
}
|
} catch (e) {
|
this.connectionStatus = "连接失败";
|
plus.ui.toast("连接失败:" + e);
|
}
|
},
|
sendPrintCommand(cmd) {
|
try {
|
if (!this.bluetoothSocket || !this.bluetoothSocket.isConnected()) {
|
plus.ui.toast("请先连接打印机");
|
return;
|
}
|
|
const outputStream = this.bluetoothSocket.getOutputStream();
|
plus.android.importClass(outputStream);
|
const arrayBuffer = plus.android.invoke(cmd, "getBytes", "gbk");
|
outputStream.write(arrayBuffer);
|
outputStream.flush();
|
plus.ui.toast("打印命令发送成功");
|
} catch (e) {
|
plus.ui.toast("打印命令发送失败:" + e);
|
}
|
},
|
print() {
|
if (this.printCmd) {
|
this.sendPrintCommand(this.printCmd);
|
}
|
},
|
printTest() {
|
const testCmd = "! 0 203 203 490 1\r\nTEXT 24 0 100 100 测试打印\r\nPRINT\r\n";
|
this.sendPrintCommand(testCmd);
|
}
|
},
|
mounted() {
|
this.initBluetooth();
|
this.connectPrinter();
|
this.print(); // 自动执行传入的打印命令
|
}
|
};
|
</script>
|
|
<style>
|
/* 样式省略 */
|
</style>
|