当前位置:网站首页>Jd-h5 development
Jd-h5 development
2022-07-22 15:59:00 【Get lazy】
Catalog
Write configuration
establish vue project
npm init [email protected] beimao-h5 -- --template vue-ts
We use -h5
npm i @nutui/nutui
stay src Inside main In file
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// Be careful : This method will import all components
import NutUI from "@nutui/nutui";
// When using on-demand loading This global css style , You need to remove
import "@nutui/nutui/dist/style.css";
createApp(App).use(NutUI).mount("#app");
Plug in package.json
{
"name": "beimao-h5",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"@nutui/nutui": "^3.1.22",
"axios": "^0.27.2",
"dayjs": "^1.11.3",
"path": "^0.12.7",
"pinia": "^2.0.14",
"pinia-plugin-persist": "^1.0.0",
"ts-md5": "^1.2.11",
"vue": "^3.2.37",
"vue-router": "^4.0.16"
},
"devDependencies": {
"@vitejs/plugin-vue": "^3.0.0",
"typescript": "^4.6.4",
"vite": "^3.0.0",
"vue-tsc": "^0.38.4"
}
}
Install after adding
npm install
stay src Of main.ts Add something inside
import { createApp } from 'vue'
import App from './App.vue'
// Import our routing file
import Router from './router/index'
// Import store
import store from './store/index'
// Be careful : This method will import all components
import NutUI from "@nutui/nutui";
// When using on-demand loading This global css style , You need to remove
import "@nutui/nutui/dist/style.css";
const app = createApp(App)
// Use Jingdong NutUI
.use(NutUI)
// Practical routing
app.use(Router)
// Use store
app.use(store);
app.mount('#app')
According to the contents , Add the corresponding folder and ts file
Join in router Folder , Create inside index.ts file , There are routes
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: '/',
name: "home",
component: () => import("@/views/Index.vue"),
},
{
path: '/category',
name: "category",
component: () => import("@/views/Category.vue"),
},
]
const router = createRouter({
history: createWebHashHistory('/'),
routes
})
export default router
establish store Folder , Create inside index.ts Files and appStore.ts file
index.ts file
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store
appStore.ts file
import { defineStore } from 'pinia'
const appStore = defineStore({
id: 'app',
state: () => {
return {
user: { id: 0, userId: "" },
token: "",
}
},
getters: {
},
actions: {
},
// Turn on the data cache
persist: {
enabled: true,
strategies: [
{
key: 'com.beiyou.h5',
storage: localStorage,
}
]
}
})
export default appStore;
establish views Folder , It establishes Index.vue
Index.vue
<template>
<div> Hello, teacher Cang </div>
</template>
In the outer vite.config.ts File to configure the file
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
port: 4000, // You need to define the port number
proxy: {
"/api": {
target: "http://localhost:8080/",
changeOrigin: true,
},
},
},
resolve: {
// Configure path alias
alias: {
'@': path.resolve(__dirname, './src'),
}
},
})
When path When it's red , install path
npm install path
Delete components The documents inside
stay src Under the folder App Contents modified in the document
<template>
<div>
home
</div>
</template>
<script setup lang="ts">
</script>
establish http Folder management page interception
establish index.ts
import axios, {
AxiosRequestConfig,
AxiosRequestHeaders,
AxiosResponse,
} from "axios";
import { storeToRefs } from "pinia";
import appStore from "@/store/appStore";
let { token } = storeToRefs(appStore());
const state = {
ok: 0,// Request success status code
401: "ERR_BAD_REQUEST"
};
// Return data rules
interface IResponseData<T> {
status: number;
message?: string;
data: T;
code: string;
}
// Request default configuration rules
type TOption = {
baseURL: string;
timeout: number;
};
// The default configuration
const config = {
baseURL: "",
timeout: 30 * 1000,
withCredentials: true,
};
let loading: any = null;
class Http {
service: any;
constructor(config: TOption) {
// Instantiate request configuration
this.service = axios.create(config);
// Request to intercept
this.service.interceptors.request.use(
(config: AxiosRequestConfig) => {
// loading = ElLoading.service({ fullscreen: true, text: ' Loading ...' });
if (token.value) {
(config.headers as AxiosRequestHeaders).Authorization = token.value;
}
return config;
},
(error: any) => {
loading.close();
return Promise.reject(error);
}
);
// The response to intercept
this.service.interceptors.response.use(
(response: AxiosResponse) => {
// loading.close();
const data = response.data;
const { code } = data;
if (code == undefined) {
// If no status code is returned , Direct return data , The returned data is blob type
return response;
} else if (code !== 0) {
//ElMessage.error(data.message);
return Promise.reject(data);
}
// code == 0 When , Extract what we only focus on Api data data
// console.log(response);
return response.data.data;
},
(error: any) => {
loading.close();
if (error.code === state[401]) {
// ElMessage.error(" request was aborted :" + error.message);
setTimeout(() => {
localStorage.removeItem('com.beiyou.h5')
window.location.href = '/#/login'
}, 1000);
}
return Promise.reject(error);
}
);
}
get<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.get(url, { params, ...data });
}
post<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.post(url, params, data);
}
put<T>(url: string, params?: object, data = {}): Promise<IResponseData<T>> {
return this.service.put(url, params, data);
}
delete<T>(
url: string,
params?: object,
data = {}
): Promise<IResponseData<T>> {
return this.service.delete(url, { params, ...data });
}
}
export default new Http(config);
Some configurations are popular in tsconfig.json Join in
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
The overall appearance after joining
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": [
"ESNext",
"DOM"
],
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
The above is all the configured files and the composition in the files
So far, the configuration we should have has been configured , The next step is to write the interface
Write interface
stay src Of App.vue Write in
<template>
<router-view></router-view>
<nut-tabbar @tab-switch="tabSwitch" :bottom="true">
<nut-tabbar-item tab-title=" home page " icon="home"></nut-tabbar-item>
<nut-tabbar-item tab-title=" classification " icon="category"></nut-tabbar-item>
<nut-tabbar-item tab-title=" Find out " icon="find"></nut-tabbar-item>
<nut-tabbar-item tab-title=" The shopping cart " icon="cart"></nut-tabbar-item>
<nut-tabbar-item tab-title=" my " icon="my"></nut-tabbar-item>
</nut-tabbar>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const tabSwitch = (item: any, index: any) => {
console.log(item, index);
if (index === 1) {
router.push({ name: "category" });
}
if (index === 0) {
router.push({ name: "home" });
}
};
</script>
<template>
<router-view></router-view>
<nut-tabbar @tab-switch="tabSwitch" :bottom="true">
<nut-tabbar-item tab-title=" home page " icon="home"></nut-tabbar-item>
<nut-tabbar-item tab-title=" classification " icon="category"></nut-tabbar-item>
<nut-tabbar-item tab-title=" Find out " icon="find"></nut-tabbar-item>
<nut-tabbar-item tab-title=" The shopping cart " icon="cart"></nut-tabbar-item>
<nut-tabbar-item tab-title=" my " icon="my"></nut-tabbar-item>
</nut-tabbar>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const tabSwitch = (item: any, index: any) => {
console.log(item, index);
if (index === 1) {
router.push({ name: "category" });
}
if (index === 0) {
router.push({ name: "home" });
}
};
</script>
analysis :
<router-view></router-view>: Support page Jump
:bottom="true": Let the following homepage wait at the bottom
Here we need to add a branch to the route , yes category Routing branch of
{
path: '/category',
name: "category",
component: () => import("@/views/Category.vue"),
},
stay views It creates Category.vue File is written to
<template> This is the classification page </template>
Start writing formally vue
Add a scrolling bulletin board to the main page
<nut-noticebar text=" Huawei Changxiang 9 The new product will be on the market " :scrollable="true" :background="`rgba(251, 248, 220, 1)`" :color="`#D9500B`"></nut-noticebar>
Add a rotation chart under the bulletin board
<nut-swiper :init-page="page" :pagination-visible="true" pagination-color="#426543" auto-play="3000">
<nut-swiper-item v-for="item in list" :key="item">
<img :src="item" alt="" />
</nut-swiper-item>
</nut-swiper>
Of a carousel script
import { reactive, toRefs, onMounted } from 'vue';
export default {
setup() {
const state = reactive({
page: 2,
list: [
'https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg',
'https://storage.360buyimg.com/jdc-article/NutUItaro2.jpg',
'https://storage.360buyimg.com/jdc-article/welcomenutui.jpg',
'https://storage.360buyimg.com/jdc-article/fristfabu.jpg'
]
});
onMounted(() => {
setTimeout(() => {
state.list.splice(1, 1);
}, 3000);
});
return { ...toRefs(state) };
}
};
Style of rotation chart
<style lang="scss" scoped>
.nut-swiper-item {
line-height: 150px;
img {
width: 100%;
height: 100%;
}
}
</style>
边栏推荐
- Albumin nanoparticles / gossypol albumin nanoparticles / lapatinib albumin nanoparticles coated with DNA and photosensitizer CE6
- [fiddlertx plug-in] use Fiddler to capture Tencent classroom video download
- QT笔记——自定义的QListWidget
- 2022.7.21 special matrix compression
- 命令行程序测试自动化
- Redis high availability principle master-slave sentinel cluster
- ctfshow MengXIn 下
- Enregistrer un résumé de la mesure de pression jmeter
- Industry digitalization has accelerated in an all-round way, and Intelligent Cloud 2.0 redefines digital transformation
- C language question bank part.1
猜你喜欢
替尼泊苷多层包衣白蛋白纳米粒/人血清白蛋白-聚己内酯纳米的制备
[learn rust together] rust preparation before learning -- Annotation and formatted output
BCH编码译码误码率性能matlab仿真
GeneralizedRCNN:features = OrderedDict([(“0“, features)])
Only es works well when checking the log? You didn't use Clickhouse like this
Detailed teaching of address book in C language
Scala变量和数据类型(2)
元宇宙赋能场景金融:商业银行竞争发展新赛道
Px4 module design Xi: built in framework
JS array object sorting (ES6)
随机推荐
Web3 社交协议垄断性与灵魂绑定代币
StrMultiplyStr
MySQL advanced addition, deletion, modification and query operations, including detailed explanation and operation of various queries and table design explanation
ctfshow MengXIn 下
白蛋白索拉非尼/Gd2O3/CuS复合白蛋白纳米粒/ALB-ICG-DOX白蛋白纳米粒包ICG&DOX的制备
Social e-commerce: chain 2+1-entry fast fission mode
LeetCode高频题:二叉树的锯齿形(Z字形,之字形)层序遍历
[error] solution: not creating XLA devices, TF_ xla_ enable_ xla_ devices not set
Do you know lumen and Nanite? How to use it in ue5 scene production?
Ctfshow Mengxin lower
C语言实现通讯录详细教学
SCM peripheral devices learning strategies, small Bai must see
Record a summary of JMeter pressure test practice
Don't look for it, it's all sorted out for you -- complete collection of SQL statements
区间贪心问题整理
高中学历自学测试,21岁在深圳拿10k,付出多少只有我自己知道~
Check for degenerate boxes
C language to write 99 multiplication table to realize the output of tables with different triangle shapes
What preliminary work does the enterprise need to do to establish its own applet and app?
Use of select function in socket communication