头图

alova? What the hell is this?

It's normal that you haven't heard of it. It is an RSM implementation library that 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.

For a detailed understanding of RSM, please refer to RSM: A Super Practical Multi-Scenario 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-side status across modules, and fuzzy search
  2. How alova assists in managing the server state under the vue project
  3. Smooth use of alova

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 installation: npm install alova --save-dev

Initialize an alova instance

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

 import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import VueHook from 'alova/vue';
const alovaInstance = createAlova({
  // 假设我们需要与这个域名的服务器交互
  baseURL: 'https://api.todo.com',

  // 在vue项目下引入VueHook,它可以帮我们用vue的ref函数创建请求相关的,可以被alova管理的状态
  statesHook: VueHook,

  // 请求适配器,这里我们使用fetch请求适配器
  requestAdapter: GlobalFetch(),
  
  // 设置全局的请求拦截器,与axios相似
  beforeRequest(config) {
    // 假设我们需要添加token到请求头
    config.headers.token = 'token';
  },

  // 响应拦截器,也与axios类似
  async responsed(response, config) => {
      const json = await response.json();
      if (json.code !== 200) {
        // 这边抛出错误时,将会进入请求失败拦截器内
        throw new Error(json.message);
      }
      return json.data;
    },
});

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

Our interface in this demo looks like this.

企业微信截图_20220914164328.png

We use useRequest to send the request, which is the most common method when the page gets initialized data.

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

const {
  // loading是加载状态值,当加载时它的值为true,结束后自动更新为false
  // 它是一个Ref类型的值,你可以通过loading.value访问它,或直接绑定到界面中
  loading,

  // 响应数据
  data: todoList,

  // 请求错误对象,请求错误时有值,否则为undefined
  error,

  // 成功回调绑定
  onSuccess,

  // 失败回调绑定
  onError,

  // 完成回调绑定
  onComplete,

  // 直接将Method对象传入即可发送请求
} = useRequest(todoListGetter, {
  // 初始data数据
  initialData: [],
});

// ###### 回调设置
onSuccess(todoListRaw => {
  console.log('请求成功,响应数据为:', todoListRaw);
});
onError(error => {
  console.log('请求失败,错误信息为:', error);
});
onComplete(() => {
  console.log('请求完成,不管成功失败都会调用');
});

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>

todo edit page - cache frequently requested data in memory

The edit page looks like this:

企业微信截图_20220914164337.png

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}`, {
    // 设置5分钟的本地内存缓存,刷新即失效
    localeCache: 5 * 60 * 1000,
});
const {
  loading,

  // 响应数据
  data: todoDetail,

  error,
} = useRequest(todoDetail(params.id));

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">提交数据</button>
</div>

Data submission code - manually update todo list data

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

  // 手动发送器请求的函数,调用后发送请求
  send: submitTodo,
} = useRequest(() => createTodoPoster(todoDetail.value), {
  // 当immediate为false时,初始化时不再发出请求
  immediate: false
});


// 手动发送请求
const handleAddTodo = () => {
  submitTodo()
    .then(result => {
      // 更新列表数据,获取todo列表状态,返回更新后的数据
      updateState(todoDetail(params.id), todoListData => {
          const index = todoListData.findIndex(({ id }) => id === params.id);
          todoListData[index] = todoDetail.value;
          return todoListData;
      });
    })
    .catch(error => {
      console.log('新增todo项失败,错误信息为:', error);
    });
};

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}`);

// 通过useWatcher监听keyword变化,变化后自动重新发出请求
const keyword = ref('');
const {
    loading,
    data,
} = useWatcher(() => searchTodo(keyword.value), [keyword], {
    debounce: 500, // 设置500毫秒防抖
});

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.


爱编程的小金
39 声望7 粉丝

爱研究各种技术的小金