index.vue 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <template>
  2. <div class="h-[calc(100vh-var(--top-tool-height)-var(--app-footer-height)-40px)] -m-5 flex">
  3. <Left :is-writing="isWriting" class="h-full" @submit="submit" @example="example" />
  4. <Right
  5. :is-writing="isWriting"
  6. @stop-stream="stopStream"
  7. ref="rightRef"
  8. class="flex-grow"
  9. v-model:msg="msgResult"
  10. />
  11. </div>
  12. </template>
  13. <script setup lang="ts">
  14. import Left from './components/Left.vue'
  15. import Right from './components/Right.vue'
  16. import { writeStream } from '@/api/ai/writer'
  17. import dataJson from './data.json'
  18. const message = useMessage()
  19. const msgResult = ref('')
  20. const isWriting = ref(false)
  21. const abortController = ref<AbortController>()
  22. const stopStream = () => {
  23. abortController.value?.abort()
  24. isWriting.value = false
  25. }
  26. const rightRef = ref<InstanceType<typeof Right>>()
  27. // 点击示例触发
  28. const example = (type: keyof typeof dataJson) => {
  29. msgResult.value = dataJson[type].data
  30. }
  31. const submit = async (data) => {
  32. abortController.value = new AbortController()
  33. msgResult.value = ''
  34. isWriting.value = true
  35. writeStream({
  36. data,
  37. onMessage: async (res) => {
  38. const { code, data, msg } = JSON.parse(res.data)
  39. if (code !== 0) {
  40. message.alert(`写作异常! ${msg}`)
  41. stopStream()
  42. return
  43. }
  44. msgResult.value = msgResult.value + data
  45. nextTick(() => {
  46. rightRef.value?.scrollToBottom()
  47. })
  48. },
  49. ctrl: abortController.value,
  50. onClose: stopStream,
  51. onError: stopStream
  52. })
  53. }
  54. </script>