In this paper, a personal blog address: www.abeille.top/posts/detai…
In the process of developing Leafage website, I tried component libraries such as Viewui (originally called iView), Element-UI, Ant Design Vue and Vuetify. However, I will find later that it is relatively easy to develop interfaces using component libraries, but there are many limitations. Also, a lot of the documentation is not well written, the slightly more complex composition or configuration is difficult to implement, and the most important thing is that several component libraries, besides vuetify, do not support responsiveness by default. They need to be adapted. Later I found that the official website of nuxtjs uses tailwindcss. Bulma and tailwindcss are both developed from CSS and do not contain any framework dependencies. Bulma is more similar to bootstrap, except that it does not rely on jquery or any Javascript. Select tailwindcss.
As a programmer, Java development from scratch to write front end, also need not component library, it is hard to pain, then find a good template to imitate, always easy, and then began to snare the template site, some template may need to spend a few dollars, buy a self satisfaction, and then reference to write or modify directly.
After the page is developed, you need to request the service interface, and since the backend service is not developed yet, you need to use mock.js to simulate the API.
First install the mock.js dependency:
yarn add mock.js -D
Copy the code
Once installed, open the plugins directory, add the mock.ts file (or create mock.js if javascript is used), and configure the mock interface as shown in the following example:
import Mock from 'mockjs'
Mock.mock(/posts\.json/, {
'list|1-10': [{
'id|+1': 1.'title': 'my title'}]})Copy the code
After the configuration is complete, you need to configure it in the nuxt.config.ts file for the configuration to take effect. Otherwise, the default configuration takes effect.
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
'~/plugins/mock'].Copy the code
The next step is to use axios to request the interface and get the data.
1. Configure AxiOS
Because the AXIos tool was installed when you initialized the project, you can now use Axios to request data from pages (.vue in the Pages directory) or components (.vue in the Components directory). Nuxtjs configures some axios configurations by default. If you want to do some of your own configuration, create axios.ts files in your plugins directory and set them as follows:
import { Plugin } from '@nuxt/types'
import { AxiosRequestConfig, AxiosError } from 'axios'
const statusCode: any = {
400: 'Request parameter error'.401: 'Insufficient permissions, please log in again'.403: 'Server denied this access'.500: 'Internal server error'.501: 'Server does not support method used in request'.502: 'Gateway error'.504: 'Gateway timed out'
}
export const accessor: Plugin = ({ error, app: { $axios }, redirect }) = > {
$axios.onRequest((config: AxiosRequestConfig) = > {
return config
})
$axios.onError((err: AxiosError<any>) = > {
const status: any= err.response? .statusif (status === 404) {
redirect('/error')}else {
error({ message: statusCode[status] })
return Promise.reject(err)
}
})
}
Copy the code
Note that when using typescript, when axios is introduced, it’s not
import axios form 'axios'
Copy the code
Instead, you need to import Plugin via @nuxt/types, and then axios’s AxiosRequestConfig and AxiosError if more axios attributes are used;
import { Plugin } from '@nuxt/types'
import { AxiosRequestConfig, AxiosError } from 'axios
Copy the code
As with Mockjs, once configured, you need to add this configuration file under plugins in nuxt.config.ts;
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
'~/plugins/mock'.'~/plugins/axios'].Copy the code
2. Use Axios
Refer to axios official document (axios-js.com/zh-cn/docs/) for basic usage methods, including synchronous request, asynchronous request, concurrent request, etc.
In addition to the general scenario of using AXIos in vue hooks, nuxtJS provides two other functions that request data, fetch() and asyncData(), for the timing of rendering.
Both functions have in common an asynchronous function, so we need to await the keyword.
AsyncData () :
-
It can only be used in pages, i.e. in a. Vue file in the Pages directory. It blocks page loading, so it cannot request a large amount of data or many synchronization interfaces.
-
Cannot use this keyword;
-
Cannot be called, only executed automatically when the page loads;
The fetch () :
-
It can be used in components or pages, in. Vue files in the Components directory and pages directory.
-
You can use this keyword;
-
Calls can be repeated, i.e. fetch() is called directly in the component to retrieve the data;
For the use of both functions, let’s use the following example to see how they can be used:
The fetch () example:
import { defineComponent } from "@vue/composition-api";
import { SERVER_URL } from "~/assets/request";
export default defineComponent({
name: "Main".async fetch() {
this.datas = await this.$axios
.get(SERVER_URL.posts.concat("? page=0&size=10&order=".this.order))
.then((res) = > res.data);
},
data() {
return {
datas: [].order: "likes"}; },methods: {
retrieve(order: string) {
this.order = order;
this.$fetch(); Fetch () is called here to reuse the interface request,}}});Copy the code
The example shows the use of the fetch() request interface and how it is invoked in other functions;
In addition, using fetch(), there is a $fetchState to determine the execution of fetch(), which can handle different page logic depending on the situation, as shown in the following example:
<div>
<p v-if="$fetchState.pending">Fetching mountains...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<div v-else class="mb-12">
</div>
</div>
Copy the code
AsyncData example:
import { defineComponent } from "@vue/composition-api";
import { SERVER_URL } from "~/assets/request";
export default defineComponent({
name: "Portfolio".scrollToTop: true.// This configuration will automatically scroll to the top of the page when loading
async asyncData({ app: { $axios } }) { // asyncData() cannot use the this keyword, so some global configuration parameters are introduced by way of an input, and axios is required
let [datas, categories] = await Promise.all([
await $axios.$get(SERVER_URL.portfolio.concat("? page=0&size=10")),
await $axios.$get(SERVER_URL.category.concat("? page=0&size=5")));return { datas, categories };
},
data() {
return {
code: "".datas: [],}; },methods: {
retrieve(code: string) {
this.code = code;
this.$axios
.get(SERVER_URL.portfolio.concat("? page=0&size=12&category=", code))
.then((res) = > (this.datas = res.data)); }},head() {
const title = "Portfolio - Leafage";
const description =
"Leafage works collection, including travel records, life sharing and other resource information, to provide original, high-quality and complete content";
return {
title,
meta: [{hid: "description".name: "description".content: description },
// Open Graph
{ hid: "og:title".property: "og:title".content: title },
{
hid: "og:description".property: "og:description".content: description,
},
// Twitter Card
{ hid: "twitter:title".name: "twitter:title".content: title },
{
hid: "twitter:description".name: "twitter:description".content: description, }, ], }; }});Copy the code
The asyncData() function is used with the object argument app: {axios}, because asyncData() is executed before the component is initialized, it can only be used by introducing a globally pending configuration, also passing store, route,route, route,router, etc.
Several template sites are recommended:
- www.bootstrapmb.com/
- tailwindcomponents.com/
- www.mobantu.com/6548.html