1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <template>
- <page-head :title="title"></page-head>
- <button class="button" type="primary" @click="connect">连接</button>
- <button class="button" type="primary" @click="close">关闭</button>
- <!-- #ifdef APP -->
- <scroll-view style="flex:1">
- <!-- #endif -->
- <view>
- <text style="width: 100%; text-align: center; margin-bottom: 5px;">
- 显示简易操作日志(可滚动查看)
- </text>
- <button size="mini" @click="logList = []">清空日志</button>
- <view style="margin-top: 10px;">
- <view v-for="(item, index) in logList" :key="index">
- <text style="margin-left: 20px; margin-right: 20px;">
- {{ item }}
- </text>
- </view>
- </view>
- </view>
- <!-- #ifdef APP -->
- </scroll-view>
- <!-- #endif -->
- </template>
- <script>
- export default {
- data() {
- return {
- logList: [] as string[],
- title: 'sse',
- url: 'https://request.dcloud.net.cn/api/sse/connect',
- eventSource: null as UniEventSource | null,
- open: false,
- receiveMessage: false
- }
- },
- unmounted() {
- if (this.eventSource != null) {
- this.eventSource?.close()
- }
- },
- methods: {
- connect() {
- console.log('connect start')
- uni.showLoading({
- title: "",
- mask: true
- })
- this.eventSource?.close()
- let headers : UTSJSONObject = new UTSJSONObject()
- headers.set("header1", "value1")
- headers.set("header2", "value3")
- this.eventSource = uni.connectEventSource({
- url: this.url,
- header: headers
- })
- this.eventSource?.onMessage((ev) => {
- const log = 'onMessage callback:' + '\n' + 'type: ' + ev.type + '\n' + 'data: ' + ev.data + '\n\n'
- this.logList.push(log)
- this.receiveMessage = true
- uni.hideLoading()
- })
- this.eventSource?.onOpen((ev) => {
- const log = 'onOpen callback: ' + ev.type + '\n\n'
- this.logList.push(log)
- this.open = true
- })
- this.eventSource?.onError((err) => {
- const log = `onError callback: ${err} \n\n`
- this.logList.push(log)
- uni.hideLoading()
- })
- },
- close() {
- this.eventSource?.close()
- const log = 'connect close' + '\n\n'
- this.logList.push(log)
- }
- }
- }
- </script>
- <style>
- .button {
- margin-left: 30px;
- margin-right: 30px;
- margin-bottom: 15px;
- }
- </style>
|