Practical skills and data caching of uni-app

Table of contents

Foreword:

1. Data cache

1. uni.setStorageSync 和 uni.getStorageSync

2. uni.setStorage and uni.getStorage

二、uni.addInterceptor(STRING, OBJECT) 

3. Cloud function

Four, request

5. Life cycle

6. Cloud server (Dcloud)

6.1. Introduction to dcloud

6.2. Cloud Server

7. Cloud packaging

Summarize:


data cache request
cloud packaging life cycle
cloud function Cloud server (Dcloud)

Foreword:

uni-app is the first choice for small program development. I have taken this course this semester, so I will share some content of uni-app with you.

uni-app is a development framework based on Vue.js, which can be used to quickly build cross-platform applications, including multiple platforms such as iOS, Android, H5 and applets.

 


 

1. Data cache

The data cache of uni-app refers to the local storage of data, so that the data can be obtained directly from the local in the next visit, which improves the performance and user experience of the program. uni-app provides two data caching methods:

1. uni.setStorageSync 和 uni.getStorageSync

Data can be stored in localStorage through uni.setStorageSync, and data can be read from localStorage through uni.getStorageSync.

Example:\sum


// 存储数据 
uni.setStorageSync('name', '张三'); 
// 读取数据 
var name = uni.getStorageSync('name'); 

2. uni.setStorage and uni.getStorage

Data can be stored in storage through uni.setStorage, and data can be read from storage through uni.getStorage.

Example:


// 存储数据 
uni.setStorage({ 
  key: 'age', 
  data: 20, 
  success: function () { 
    console.log('存储成功') 
  } 
}) 
// 读取数据 
uni.getStorage({ 
  key: 'age', 
  success: function (res) { 
    console.log('读取成功', res.data) 
  } 
}) 

It should be noted that the storage and reading of storage are asynchronous, and the result needs to be obtained through the success callback. In addition, both localStorage and storage have certain storage capacity limitations, which need to be selected according to the actual situation.


二、uni.addInterceptor(STRING, OBJECT) 

uni.addInterceptor(STRING, OBJECT) is a UniApp API. This function can add an interceptor to the global Interceptor (interceptor). It accepts two parameters: string STRING and object OBJECT.

Among them, STRING is the matching rule of the URL of the HTTP request to be intercepted, which can be represented by a string or a regular expression. For example, you can use the string "/api/*" to indicate that all URL requests starting with "/api/" are intercepted; or use the regular expression /\/api.*/ to indicate that all URL requests starting with "/api" are intercepted.

And OBJECT is an interceptor object, which contains a series of interceptor methods, such as  request, response etc. These methods will be automatically called when events such as before the HTTP request is initiated, when the response arrives, etc., so as to realize the interception and processing of the HTTP request. It is possible to modify the request or add some additional processing in the interceptor before sending the request to the server. When the server returns a response, the interceptor will process the response before the response data is applied.

Through this method, we can globally intercept and process all HTTP requests when doing front-end development, so as to achieve unified processing of requests, simplify the development process, and improve code quality.

3. Cloud function


Uni-app cloud function is a back-end development solution with less server architecture running in the cloud. With the help of uniCloud, it can realize a fast, safe, efficient, and elastic development process.

The main features of Uni-app cloud functions include:

1. Support the mainstream Node.js operating environment, integrate many npm packages, and easily write and debug JavaScript back-end code;

2. Cloud functions can be quickly created and deployed, and various application scenarios such as API interfaces, timing tasks, and data storage can be realized through cloud functions;

3. It can realize the seamless integration with the Uni-app front-end project, directly call the cloud function interface, obtain the return value, and improve the development efficiency;

4. Integrates a variety of security measures, such as anti-leeching, anti-DDos attacks, etc., to ensure the data security and service reliability of cloud functions;

5. You can flexibly choose the geographical location, network environment and computing resources to meet different business needs.

In general, Uni-app cloud function is a cloud solution suitable for developers to quickly build efficient back-end services, which can help developers complete the development and deployment of business logic in a short period of time, improving development efficiency and security.


Four, request

uni.request of uni-app is an API interface that can be used to send HTTP requests. It uses Promise objects to return results, supports Promise-based asynchronous programming style, and provides some rich configuration options and callback functions.

uni.request supports sending different types of requests, such as GET, POST, PUT, DELETE, etc. It also supports uploading and downloading files and setting request header information. At the same time, it also supports interception and cancellation of network requests, and allows developers to set request timeouts.

In addition, uni.request also supports displaying loading animations during the request process, and displays error messages when the request fails. It is very suitable for Web API calls and data interaction operations in uni-app.

Example:\prod

uni.request({
  url: 'https://api.example.com/users',
  method: 'GET',
  data: {
    page: 1,
    limit: 10
  },
  header: {
    'Content-Type': 'application/json'
  },
  success: function (res) {
    console.log(res.data);
  },
  fail: function (err) {
    console.error(err);
  }
});

In the above example, uni.requestthe method receives a configuration object as a parameter, including the following options:

  • url: The requested URL address.
  • method: The method of the request, such as GET, , POSTetc., the default is GET.
  • data: The data to be sent GETwill be converted into a query string in the request.
  • header: The requested header information.
  • success: The callback function when the request is successful, receiving the response data as a parameter.
  • fail: The callback function when the request fails, receiving the error message as a parameter.

Modify the URL address, request method, request data, request header, etc. in the above examples to meet your actual needs.

It should be noted that uni.requestthe method is asynchronous, so you need to successhandle the response data in the callback function or failhandle the request failure in the callback function.

In addition uni.request, uni-app also provides other network request methods, such as uni.uploadFilefor file upload and uni.downloadFilefile download. You can choose a suitable method to make network requests according to your needs.

5. Life cycle

uni-app is a cross-platform application development framework based on Vue.js, which can be used to simultaneously develop applications for multiple platforms such as iOS, Android, H5 and applets. The life cycle of uni-app is similar to that of Vue.js, but it also has some specific life cycle hook functions. The following is the main life cycle of uni-app:

1. `beforeCreate` (beforeCreate): After the instance is initialized, it is called before data observation and event configuration.

export default {
  beforeCreate() {
    // 执行一些初始化逻辑操作
    console.log('beforeCreate hook executed');
  },
  data() {
    return {
      message: 'Hello, world!'
    };
  },
  methods: {
    greet() {
      console.log(this.message);
    }
  },
  mounted() {
    // 在mounted钩子函数中调用greet方法
    this.greet();
  }
};

2. `created` (created): The instance has been created, data observation and event configuration have been completed, but not yet mounted on the DOM.

export default {
  created() {
    // 执行一些初始化逻辑操作
    console.log('created hook executed');
    
    // 发起异步请求
    fetchData().then(data => {
      // 对获取到的数据进行操作
      console.log(data);
    });
  },
  data() {
    return {
      message: 'Hello, world!'
    };
  },
  methods: {
    greet() {
      console.log(this.message);
    }
  },
  mounted() {
    // 在mounted钩子函数中调用greet方法
    this.greet();
  }
};

3. `beforeMount` (beforeMount): Called before the instance is mounted.

export default {
  beforeMount() {
    // 执行一些操作
    console.log('beforeMount hook executed');
    
    // 更新组件的数据
    this.message = 'Hello, uni-app!';
  },
  data() {
    return {
      message: 'Hello, world!'
    };
  },
  methods: {
    greet() {
      console.log(this.message);
    }
  },
  mounted() {
    // 在mounted钩子函数中调用greet方法
    this.greet();
  }
};

4. `mounted` (mounted): The instance has been mounted on the DOM, at this time, you can access the DOM elements of the component.

export default {
  mounted() {
    // 操作组件的DOM
    const element = this.$refs.myElement;
    element.innerText = 'Hello, uni-app!';
    
    // 发起异步请求
    fetchData().then(data => {
      // 对获取到的数据进行操作
      console.log(data);
    });
    
    // 注册事件监听器
    this.$refs.myElement.addEventListener('click', this.handleClick);
  },
  data() {
    return {
      message: 'Hello, world!'
    };
  },
  methods: {
    greet() {
      console.log(this.message);
    },
    handleClick() {
      console.log('Element clicked!');
    }
  }
};

5. `beforeUpdate` (beforeUpdate): Called before the data is updated, before the virtual DOM is re-rendered and patched.

export default {
  data() {
    return {
      message: 'Hello, world!',
      count: 0
    };
  },
  beforeUpdate() {
    // 执行一些操作
    console.log('beforeUpdate hook executed');
    
    // 访问更新前的数据
    console.log('Count before update:', this.count);
  },
  methods: {
    increment() {
      this.count++;
    }
  }
};

6. `updated` (updated): Called after the data is updated, after the virtual DOM is re-rendered and patched.

export default {
  updated() {
    // 操作更新后的DOM
    const element = this.$refs.myElement;
    element.innerText = 'Hello, updated uni-app!';
    
    // 做一些额外的数据处理
    if (this.count >= 10) {
      console.log('Count is greater than or equal to 10!');
    }
    
    // 发起异步请求
    fetchData().then(data => {
      // 对获取到的数据进行操作
      console.log(data);
    });
  },
  data() {
    return {
      message: 'Hello, world!',
      count: 0
    };
  },
  methods: {
    increment() {
      this.count++;
    }
  }
};

7. `beforeDestroy` (beforeDestroy): Called before the instance is destroyed. At this time, the instance is still fully available.

export default {
  beforeDestroy() {
    // 清理定时器
    clearInterval(this.timer);
    
    // 移除事件监听器
    this.$refs.myElement.removeEventListener('click', this.handleClick);
    
    // 执行清理逻辑
    cleanup();
  },
  mounted() {
    // 创建定时器
    this.timer = setInterval(() => {
      console.log('Timer tick');
    }, 1000);
    
    // 注册事件监听器
    this.$refs.myElement.addEventListener('click', this.handleClick);
  },
  methods: {
    handleClick() {
      console.log('Element clicked!');
    },
    cleanup() {
      console.log('Cleaning up...');
    }
  }
};

8. `destroyed` (destroyed): Called after the instance is destroyed. At this time, the component has been destroyed, and the data and event listeners have been removed.

export default {
  destroyed() {
    // 清除资源
    releaseResources();
    
    // 发送销毁通知
    this.$emit('component-destroyed');
  },
  mounted() {
    // 做一些初始化操作
    initialize();
  }
};

In addition to the common lifecycle hook functions mentioned above, uni-app also provides some platform-specific lifecycle hook functions:

- `onLaunch` (applet): Triggered when the application is initialized.
- `onShow` (applet): Fired when the app starts or enters the foreground from the background.
- `onHide` (applet): Triggered when the application enters the background from the foreground.
- `onError` (applet): Triggered when an error occurs in the application.
- `onPageNotFound` (applet): Triggered when the page is not found.

These lifecycle hook functions allow developers to execute specific code logic at different stages of the application to achieve corresponding functions and operations. For detailed usage methods and precautions of lifecycle hook functions, please refer to the official documentation of uni-app.

6. Cloud server (Dcloud)

6.1. Introduction to Dcloud

DCloud is a company that provides uni-app cross-platform development framework and cloud services, not a specific cloud server provider. DCloud provides a cloud packaging service based on the HBuilderX development tool. Developers can use this service to quickly package uni-app applications into small programs, Apps, and H5, and publish them to various platforms.

When developers use DCloud cloud packaging service, DCloud will provide a cloud-based construction environment and resources for packaging uni-app applications written by developers into executable files or web pages under various platforms. Developers do not need to configure the server environment themselves, but only need to upload the application code and configure related options, and DCloud will automatically build and package it.

It should be noted that the DCloud cloud service is aimed at uni-app developers to simplify the application packaging and publishing process, and provides some additional functions and services, such as automatic updates, cloud functions and cloud databases, etc., to meet the needs of developers.

However, if you need to build your own cloud server to host the uni-app application, you can choose other common cloud server providers (such as Alibaba Cloud, Tencent Cloud, AWS, etc.) or deploy it through your own server. These cloud server providers can meet the basic operating requirements of uni-app applications and provide a certain degree of flexibility and scalability.

6.2. Cloud Server

For cloud servers for uni-app applications, you can deploy them to various cloud service providers or your own private servers. Here are some common cloud server options:

1. Cloud Service Providers (Cloud Service Providers): such as Alibaba Cloud, Tencent Cloud, AWS (Amazon Cloud Services), Google Cloud, etc. , which provide various cloud computing services and resources, including virtual machines, containers, object storage, databases, etc. You can choose a cloud server instance that suits your application needs and budget for deployment. Generally use Alibaba Cloud and Tencent Cloud

2. Lightweight Container Services: such as Docker, Kubernetes, etc., which provide solutions for containerized application deployment and management. Using container services can achieve more flexible and efficient deployment methods, and can be deployed across multiple cloud platforms.

3. Private Servers: If you have your own server resources, you can choose to deploy the uni-app application to your own server. You can use virtualization technology such as KVM, VMware, etc. to create a virtual machine instance, and configure a web server environment in it to host the uni-app application.

When choosing a cloud server, you need to consider the following factors:

  • - Scalability: Ensure that the cloud server provider can elastically expand according to application needs in order to adapt to traffic growth or other changes.
  • - Performance: Select a server instance with good performance to ensure application responsiveness and user experience.
  • - Availability: Choose a cloud server that offers high availability to ensure that your applications continue to run in the event of failures or unexpected events.
  • - Cost-effectiveness: Evaluate the price and fee structures of different cloud server options and choose the one that fits your budget.

In addition, when deploying the uni-app application, you also need to set the domain name and configure the SSL certificate to achieve HTTPS access to ensure server security and data transmission protection.

You need to choose a suitable cloud server solution based on your specific needs and budget. During the deployment process, ensure configuration and management in accordance with relevant documentation and best practices, and regular security and performance optimization.

Note \cdot: Aliyun server in Dcloud can be used for free, but it cannot be upgraded, and there will be a fee for the upgrade. It is not recommended for Xiaobai to upgrade, I personally experienced it!!!!

7. Cloud packaging

uni-app cloud packaging is a cloud service provided by DCloud, which is used to quickly package uni-app applications into small programs, Apps, H5 and other forms, and publish them to various platforms.

Using uni-app cloud packaging can bring the following main advantages:

1. Fast packaging: The cloud packaging service provides an efficient packaging process and resources, which can greatly shorten the packaging time and save developers' time and energy.

2. Platform adaptation: The cloud packaging service can automatically adapt and convert according to the requirements of the target platform to ensure that the running and display effects of the application on different platforms are consistent.

3. One-click publishing: The cloud packaging service provides a one-click publishing function, allowing developers to easily publish applications to the target platform without manual configuration and debugging of complex environments.

4. Function extension: Cloud packaging service also provides some additional functions and services, such as automatic update, cloud function and cloud database, etc., so that developers can build and manage applications more conveniently.

The basic process of using uni-app cloud packaging is as follows:

1. Log in to the DCloud official website and enter the uni-app cloud packaging service page.

2. Create a new packaging task, select the target platform and configure related options.

3. Upload the code and resource files of the uni-app application.

4. Configure the application icon, name, version number and other information as required.

5. Start the packaging task and wait for the packaging to succeed.

6. After the packaging is complete, you can download the packaged application, or publish it directly to each platform.

Cloud packaging services can greatly simplify the packaging and publishing process of uni-app applications, enabling developers to bring applications to the market more quickly and efficiently without paying too much attention to underlying technical details and configurations.

Note: If cloud packaging involves cloud functions, your things will be gone when the cloud functions expire, and you can only see the shell. And the effect of packaging into a WeChat applet is different from that displayed in an app. The WeChat applet can be compatible with all your functions, but other platforms may not.

 

Summarize:

uni-app is a very easy-to-use program. It is very easy to use. I highly recommend that everyone learn to use it, and now that small programs are the mainstream, everyone should not lose their foundation in this area. I hope that my article will be helpful to everyone, so that your studies and careers can go smoothly. 

end

Guess you like

Origin blog.csdn.net/phpweiyi/article/details/131281667
Recommended