Questions about using global variables in vue

Look at the requirements first: Click Start, use fetch() to send requests, and receive data streams. Click Stop to terminate the fetch() request.

Question: To terminate the data flow requested by fecth(), the new method must be destroyed

Method 1. Create js that stores global variables

Create a new js file config in the store folder, fill in the content, and expose it

const controller = new AbortController();
const signal = controller.signal;

export {
  signal,
  controller,
}

In main.js:

import {
  signal,
  controller,
}from "@/store/config.js"

Vue.prototype.signal = signal;
Vue.prototype.controller = controller;

This can be used in vue files, for example:

this.controller.abort(); // 终止请求

Method 1 The new method is manually created. After each destruction, there is no way to re-new without refreshing. The actual operation is to click to start receiving data streams, click to stop destroying methods, and stop receiving data streams. If you want to click start again without refreshing the page, receive the data stream, and then there is no way to stop it. Only method 2

Method 2 Mount the new method on the window.

like this:

window["controller" + (index + 1)] = new AbortController();
        window["signal" + (index + 1)] =
          window["controller" + (index + 1)].signal;

My index here is to loop out multiple, and each time I click to start, I will create a new one.

Destroy when click stop:

   window["controller" + (index + 1)].abort();

In this way, the desired function can be realized very easily.

Where is wrong, welcome to discuss~

Guess you like

Origin blog.csdn.net/weixin_39891473/article/details/128647408
Recommended