DEV Community

Cover image for Getting Started with vue+alova
Scott Hu
Scott Hu

Posted on

Getting Started with vue+alova

*alova? What the hell is this? *

It's normal that you haven't heard of it. It is an RSM implementation library, which is used to solve problems in different request scenarios under the MVVM project, and can also help you manage server-side status.

It is like an armed library of axios, adding wings to axios.

To learn more about RSM, please refer to RSM: A Super Practical Multi-scene Request Management Solution

This article is a basic introduction to vue+alova. You can learn the following:

  1. How alova handles frequent requests, updates server status across modules, and fuzzy search
  2. How alova assists in managing the server state under the vue project
  3. How to use alova smoothly

In the next getting started guide, we will take todo as an example, and explain around the needs of getting todo lists for different dates, viewing todo details, and creating, editing, and deleting items!

alova install: npm install alova --save-dev

Initialize an alova instance

An alova instance is the starting point of use, and all requests need to start from it. It is written like axios, and the following is the simplest way to create an alova instance.

import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import VueHook from 'alova/vue';
const alovaInstance = createAlova({
  // Suppose we need to interact with the server for this domain
  baseURL: 'https://api.todo.com',

  // Introduce VueHook under the vue project, which can help us create request-related states that can be managed by alova using vue's ref function
  statesHook: VueHook,

  // Request adapter, here we use fetch request adapter
  requestAdapter: GlobalFetch(),

  // Set a global request interceptor, similar to axios
  beforeRequest(config) {
    // Suppose we need to add the token to the request header
    config.headers.token = 'token';
  },

  // Response interceptor, also similar to axios
  async responsed(response, config) => {
      const json = await response.json();
      if (json.code !== 200) {
        // When an error is thrown here, it will enter the request failure interceptor
        throw new Error(json.message);
      }
      return json.data;
    },
});
Enter fullscreen mode Exit fullscreen mode

todo list - directly use the state managed by alova for interface rendering

Our interface in this demo looks like this.

Image description

We send requests using useRequest, which is the most common method for pages to get initialized data.

const todoListGetter = alovaInstance.Get('/todo/list');

const {
  // loading is the loading state value, when it is loaded, its value is true, and it is automatically updated to false after the end
  // It is a value of type Ref, you can access it through loading.value, or bind directly to the interface
  loading,

  // response data
  data: todoList,

  // Request error object, it has a value when the request is wrong, otherwise it is undefined
  error,

  // successful callback binding
  onSuccess,

  // Failed callback binding
  onError,

  // complete callback binding
  onComplete,

  // Directly pass in the Method object to send the request
} = useRequest(todoListGetter, {
  // initial data data
  initialData: [],
});

// ###### callback settings
onSuccess(todoListRaw => {
  console.log('The request is successful, the response data is:', todoListRaw);
});
onError(error => {
  console.log('The request failed, the error message is:', error);
});
onComplete(() => {
  console.log('The request is completed, it will be called regardless of success or failure');
});
Enter fullscreen mode Exit fullscreen mode

Next, we render the todoList to the rendering interface, done!

<div v-if="loading">Loading...</div>
<div v-else-if="error" class="error">{{ error.message }}</div>
<template v-else>
  <div v-for="todo in todoList">
    <div class="todo-title">{{ todo.title }}</div>
    <div class="todo-time">
        <span class="time">{{ todo.startTime }}</span>
        to
        <span class="time">{{ todo.endTime }}</span>
    </div>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

todo edit page - cache frequently requested data in memory

The edit page looks like this:

Image description

Here our scenario needs to be considered. The user clicks a todo item multiple times to view it within a few seconds, and it is a bit wasteful to request the server every time he enters. At this time, we can do a layer of front-end caching to improve the display speed and reduce the pressure on the server. .

const todoDetail = id => alovaInstance. Get(`/todo/${id}`, {
    // Set a 5-minute local memory cache, refresh will be invalid
    localeCache: 5 * 60 * 1000,
});
const {
  loading,

  // response data
  data: todoDetail,

  error,
} = useRequest(todoDetail(params.id));
Enter fullscreen mode Exit fullscreen mode

page rendering code

<div v-if="loading">loading...</div>
<div v-else>
    <input v-model="todoDetail.title" />
    <input v-model="todoDetail.date" />
    <input v-model="todoDetail.startTime" />
    <input v-model="todoDetail.endTime" />
    <!-- ... -->
    <button @click="handleAddTodo">Submit data</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Data submission code - manually update todo list data

const createTodoPoster = newTodo => alova.Post('/todo', newTodo);
const {
  loading,
  data,
  error,

  // The function of the manual sender request, the request is sent after the call
  send: submitTodo,
} = useRequest(() => createTodoPoster(todoDetail.value), {
  // When immediate is false, no more requests are made during initialization
  immediate: false
});


// Manually send the request
const handleAddTodo = () => {
  submitTodo()
    .then(result => {
      // Update the list data, get the status of the todo list, and return the updated data
      updateState(todoDetail(params.id), todoListData => {
          const index = todoListData.findIndex(({ id }) => id === params.id);
          todoListData[index] = todoDetail.value;
          return todoListData;
      });
    })
    .catch(error => {
      console.log('Failed to add todo item, the error message is:', error);
    });
};
Enter fullscreen mode Exit fullscreen mode

Fuzzy search todo items

The fuzzy search function is to continuously send out requests in the process of entering keywords. In order to improve the user experience and reduce the pressure on the server, we need to implement search anti-shake.

The implementation code is as follows:

const searchTodo = keyword => alovaInstance.Get(`/todo?keyword=${keyword}`);

// Monitor keyword changes through useWatcher, and automatically re-issue the request after the change
const keyword = ref('');
const {
    loading,
    data,
} = useWatcher(() => searchTodo(keyword.value), [keyword], {
    debounce: 500, // set 500ms debounce
});
Enter fullscreen mode Exit fullscreen mode

In this way, the fuzzy search function with anti-shake is realized.

Summarize

That's all for the getting started guide in this issue. The basic usage of vue+alova is also covered. You can also try it out. Welcome to the comment area to exchange questions.

Top comments (0)