# sendMixin & XRequest
# Feature Description
A mixin for send operations that provides unified request state management and interruption control, supporting the following features:
- Supports two request methods: SSE (Server-Sent Events) and Fetch
- Provides complete request lifecycle management
- Supports request interruption control
- Automatically handles request status
- Error handling mechanism
- Supports custom data transformers
- Supports a utility function version for non-component scenarios
- Integrates the XRequest class to provide powerful request handling capabilities
# Import and Usage
import { sendMixin } from 'vue-element-ui-x';
export default {
mixins: [sendMixin],
// ...
};
Note
The import method in the following examples is to resolve an error during the documentation site's packaging. Under normal circumstances, please import it in the standard way.
# Usage Examples
# Basic Usage of sendMixin
Basic Flow
User Action → handleSend/handleAbort/handleFinish → Update loading state → Call user callback
With state control, we can easily customize the loading state of some buttons.
Click any button to start the operation. The button will automatically switch to a loading state and end after a few seconds:
Current Status: voice | Active Button: Idle
The above examples control the front-end loading state
. Of course, request state
control is also essential. Next, let's introduce the basic usage of the utility class XRequest.
# XRequest Basic Usage (sse)
The SSE request method supported by the XRequest utility class
Received Messages:
Disconnected# XRequest Basic Usage (fetch)
The fetch request method of the XRequest utility class
Received Messages:
Disconnected# Mixed Usage of sendMixin
and XRequest
Use sendMixin
for front-end state control and XRequest
for back-end request control.
# Mixin Properties
Parameter | Description | Type | Default |
---|---|---|---|
loading | Request loading state | Boolean | false |
_sendPromise | Send operation Promise | Promise | null |
_sendController | Send controller | Object | null |
# Mixin Methods
Method Name | Description | Parameters | Return Value |
---|---|---|---|
initSend | Initialize send configuration | options: { onAbort, sendHandler, abortHandler, finishHandler } | - |
handleSend | Execute send operation | ...args: Arguments passed to sendHandler | - |
handleAbort | Abort send operation | - | - |
handleFinish | Finish send operation | - | - |
createXRequest | Create XRequest instance | options: XRequest configuration options | XRequest |
# XRequest Class
# Constructor Options
Parameter | Description | Type | Default |
---|---|---|---|
baseURL | Base URL | String | '' |
type | Request type (sse/fetch) | String | 'sse' |
transformer | Data transformer | Function | - |
baseOptions | Base configuration options | Object | {} |
onAbort | Abort callback | Function | - |
onMessage | Message callback | Function | - |
onError | Error callback | Function | - |
onOpen | Connection open callback (SSE mode) | Function | - |
onFinish | Finish callback | Function | - |
# XRequest Methods
Method Name | Description | Parameters | Return Value |
---|---|---|---|
send | Send request | url: Request URL, options: options | XRequest |
abort | Abort request | - | - |
# Events
The mixin itself does not trigger events directly, but it supports configuring callback functions in initSend
:
Callback Function | Description | Callback Parameters |
---|---|---|
onAbort | Triggered when the request is aborted | - |
sendHandler | Send handler | ...args: send parameters |
abortHandler | Abort handler | - |
finishHandler | Finish handler | - |
# Utility Function Version
For non-component scenarios, a utility function version is provided:
import { createSendUtils, XRequest } from 'vue-element-ui-x';
// Create send utility
const sendUtils = createSendUtils({
sendHandler: (...args) => {
console.log('Start sending:', args);
// Execute sending logic
},
abortHandler: () => console.log('Request aborted'),
finishHandler: () => console.log('Request finished'),
onAbort: () => console.log('Abort callback'),
});
// Use utility to send request
function sendRequest() {
sendUtils.send('param1', 'param2');
}
// Abort request
function abortRequest() {
sendUtils.abort();
}
// Get current status
function getStatus() {
return {
isLoading: sendUtils.state.loading,
};
}
// Use XRequest class directly
const xRequest = new XRequest({
baseURL: 'https://api.example.com',
type: 'fetch',
transformer: data => JSON.parse(data),
onMessage: message => console.log('Message:', message),
onError: error => console.error('Error:', error),
onFinish: messages => console.log('Finished:', messages.length, 'messages'),
});
// Send request
xRequest.send('/api/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: 'hello' }),
});
// Abort request
xRequest.abort();
# Precautions
- This mixin supports modern browsers' Fetch API and EventSource API. Please ensure browser compatibility before use.
- SSE mode is suitable for server-push scenarios, while Fetch mode is for streaming response data.
- A custom
transformer
function can be used to preprocess received data. - Resources are automatically cleaned up when the component is destroyed to prevent memory leaks.
- For long-running requests, it is recommended to implement an appropriate error retry mechanism.
- The
baseOptions
configuration is only effective in SSE mode and is used for the EventSource constructor. - The
options
parameter in Fetch mode is passed to the fetch function and supports all standard fetch options.
# SSE Connection End Detection Mechanism
The XRequest class in SSE mode uses multiple detection mechanisms to accurately determine if a connection has ended normally:
- End Message Detection: Supports detecting end markers like
[DONE]
ordata: [DONE]
. - Timeout Detection: If no new message arrives within 10 seconds and the connection is not in a connecting state, it is considered ended.
- State Detection: A comprehensive judgment based on the EventSource's readyState and the number of messages received.
- Duplicate Trigger Prevention: Uses an internal flag to prevent the end event from being triggered multiple times for the same connection.
This design effectively prevents normally closed connections from being mistaken for errors, ensuring that the onFinish
and onError
callbacks are triggered correctly.
# Custom Timeout
If you need to adjust the timeout detection period, you can configure it when creating the XRequest instance:
const xRequest = new XRequest({
// Other configurations...
onMessage: msg => {
// Process message
console.log('Message received:', msg);
},
onFinish: messages => {
console.log('Connection finished normally, received', messages.length, 'messages in total');
},
onError: error => {
console.error('An error occurred with the connection:', error);
},
});
// You can customize the detection interval by modifying the instance's timeout period
// Note: This must be set before calling send
xRequest._finishTimeout = 5000; // 5-second timeout
</rewritten_file>