vite+vue3

這兩天利用晚上的時間,操作了一把vite+vue3,現在把操作過程記錄下來。

一、準備工作

首先,你需要把nodejs版本升級到12以上,官網:nodejs.org,中文站:http://nodejs.cn/,我直接下載16.14.2LTS版

然後,安裝Visual Studio Code,官網:https://code.visualstudio.com/,爲了更好的使用VSCode,根據自己的需要安裝一系列插件

二、開始工作

1.vite

1.1.簡要說明:vite是用來代替webpack的打包工具,原理是利用現代瀏覽器已經支持esmodule的import,vite通過攔截由import轉變的http請求,做一些預編譯,提升開發體驗。

1.2.步驟過程:

      a).使用npm創建工程,命令:npm init @vitejs/app。

      b).系統提示輸入工程名稱,假設名稱爲ViteVue。

      c).系統提示選擇一個框架模板,通過上下箭頭選擇,這裏當然選擇vue。此處說明,vite不是專門爲vue設計,它還支持react等其他框架模板。

      d).上述三步完成之後,基於vite的vue項目就創建完畢。

      e).進入工程目錄,命令:cd vitevue

      f).安裝依賴包,命令:npm install

1.3.查看效果:啓動項目,命令:npm run dev

 

2.vue-router

2.1.簡要說明:與vue3搭配的vue-router版本是4.x,vue-router4.x和vue-router3.x在使用的過程中有些差異,需要查看一下官方文檔。

2.2.步驟過程

      a).安裝vue-router,命令:npm install vue-router@next --save

      b).在src目錄下創建router文件夾,在文件夾下創建index.js文件

      c).在index.js文件編寫以下代碼

 1 import * as vueRouter from 'vue-router';
 2 
 3 const routes = [
 4     { 
 5         path: "/", 
 6         redirect: "/home" 
 7     },
 8     { 
 9         path: '/home', 
10         name: 'Home', 
11         component: () => import("@/views/home/index.vue") 
12     }
13 ]
14 
15 const router = vueRouter.createRouter({
16     history: vueRouter.createWebHistory(),
17     routes: routes
18 })
19 
20 export default router
View Code

      d).修改src/views/home/index.js文件內容爲以下內容

 1 <template>
 2   <HelloWorld :msg="msg"></HelloWorld>
 3 </template>
 4 
 5 <script>
 6 import HelloWorld from "@/components/HelloWorld.vue"
 7 
 8 export default ({
 9   name: "Home",
10   components: { HelloWorld },
11   setup() {
12     return {
13       msg: "hello World",
14     }
15   }
16 })
17 </script>
View Code

     e).修改main.js文件,引入vue-router,代碼如下

1 import * as Vue from 'vue'
2 
3 import App from './App.vue'
4 import router from './router/index'
5 
6 const app=Vue.createApp(App)
7 app.use(router)
8 app.mount('#app')
View Code

     f).將App.vue文件中的內容替換爲以下內容

 1 <template>
 2   <img alt="Vue logo" src="./assets/logo.png" />
 3   <router-view />
 4 </template>
 5 
 6 <script>
 7 export default {
 8   name: 'App',
 9   setup() {
10 
11   }
12 }
13 </script>
View Code

    g).修改vite.config.js文件,安裝path模塊,添加@別名

         1.安裝命令:npm install --save-dev @types/node

         2.配置文件:

 1 import { defineConfig } from 'vite'
 2 import vue from '@vitejs/plugin-vue'
 3 import path from 'path'   // 需安裝此模塊
 4 
 5 // https://vitejs.dev/config/
 6 export default defineConfig({
 7   plugins: [vue()],
 8   resolve: {
 9     alias: {
10       '@': path.resolve(__dirname, 'src')
11     }
12   }
13 })
View Code

2.3.查看效果:上述步驟過程執行完畢,運行命令:npm run dev,就看到效果了。 

 

3.vuex

3.1.簡要說明:Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式 + 庫。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。與vue3搭配的vuex版本是4.x。

3.2.步驟過程

      a).安裝vuex,命令:npm install vuex@next --save

      b).在src下創建目錄store文件夾,然後在其下創建index.js文件,內容如下

1 import Vuex from 'vuex'
2 import getters from './getters'
3 
4 const store = Vuex.createStore({
5     modules:{ },
6     getters
7 })
8 
9 export default store
View Code

      c).修改main.js文件,引入vuex,內容如下

1 import * as Vue from 'vue'
2 
3 import App from './App.vue'
4 import store from './store/index'
5 
6 const app=Vue.createApp(App)
7 app.use(store)
8 app.mount('#app')
View Code

      d).vuex4.x的使用和vuex3.x版本差別不大,這裏就不寫示例了。

3.3.查看效果:啓動項目,命令:npm run dev

 

4.elementplus

4.1.簡要說明:element團隊給搭配vue3的elementUI起了個新名字elementPlus,這裏只是記錄使用它的過程,你也可以使用阿里螞蟻團隊的ant-design-vue等。

4.2.步驟過程:

      a).安裝elementPlus,命令:npm install element-plus --save

      b).修改main.js文件,引入elementplus,代碼如下

 1 import * as Vue from 'vue'
 2 
 3 import App from './App.vue'
 4 import ElementPlus from 'element-plus'
 5 import 'element-plus/theme-chalk/index.css'
 6 import zhCn from 'element-plus/es/locale/lang/zh-cn'
 7 
 8 const app=Vue.createApp(App)
 9 app.use(ElementPlus,{locale:zhCn})
10 app.mount('#app')
View Code

      c).修改App.vue文件,編寫示例,代碼如下

 1 <template>
 2   <img alt="Vue logo" src="./assets/logo.png" />
 3 
 4   <el-form :inline="true" :model="formInline" class="demo-form-inline">
 5     <el-form-item label="審批人">
 6       <el-input v-model="formInline.user" placeholder="審批人"></el-input>
 7     </el-form-item>
 8     <el-form-item label="活動區域">
 9       <el-select v-model="formInline.region" placeholder="活動區域">
10         <el-option label="區域一" value="shanghai"></el-option>
11         <el-option label="區域二" value="beijing"></el-option>
12       </el-select>
13     </el-form-item>
14     <el-form-item>
15       <el-button type="primary" @click="onSubmit">查詢</el-button>
16     </el-form-item>
17   </el-form>
18 </template>
19 
20 <script>
21 export default {
22   data() {
23     return {
24       formInline: {
25         user: "",
26         region: "",
27       },
28     };
29   },
30 
31   methods: {
32     onSubmit() {
33       console.log("submit!");
34     },
35   },
36 };
37 </script>
View Code

4.3.查看效果:啓動項目,命令:npm run dev

 

5.axios

5.1.簡要說明:使用axios主要要把跨域問題解決好。

5.2.步驟過程

      a).安裝axios,命令:npm install axios

      b).修改App.vue文件,內容如下

 1 <template>
 2   <img alt="Vue logo" src="./assets/logo.png" />
 3   <div>
 4     {{weatherinfo.city}}
 5     {{weatherinfo.WD}}
 6     {{weatherinfo.WS}}
 7   </div>
 8 </template>
 9 
10 <script>
11 import { onMounted,reactive } from "vue";
12 import axios from "axios"
13 
14 export default defineComponent({
15   name: 'App',
16   setup() {
17     let weatherinfo = reactive({})
18 
19      onMounted(()=>{
20        axios.get(`devApi/data/sk/101010100.html`).then(res=>{
21         Object.assign( weatherinfo, res.data.weatherinfo)
22         console.log('weatherinfo', weatherinfo)
23       }).catch(err=>{
24         console.log(err)
25       })
26     })
27 
28     return { weatherinfo}
29   }
30 })
31 </script>
View Code

      c).由於涉及到跨域,修改vite.config.js文件配置代理

 1 import {defineConfig} from 'vite'
 2 import vue from '@vitejs/plugin-vue'
 3 import path from 'path'   // 需安裝此模塊
 4 import cfgSetting from './src/configs/settings'
 5 
 6 
 7 // https://vitejs.dev/config/
 8 export default defineConfig({
 9     plugins: [
10         vue()
11     ],
12     resolve: {
13         alias: {
14             '@': path.resolve(__dirname, 'src')
15         }
16     },
17     server: {
18         host: cfgSetting.spaAddress,
19         port: cfgSetting.spaPort,
20         strictPort: false,              //設爲true時端口被佔用則直接退出,不會嘗試下一個可用端口
21         cors: true,                     //爲開發服務器配置CORS, 默認啓用並允許任何源
22         open: true,                     //服務啓動時自動在瀏覽器中打開應用
23         hmr: false,                     //禁用或配置 HMR 連接
24         //傳遞給 chockidar 的文件系統監視器選項
25         watch: {
26           ignored:["!**/node_modules/your-package-name/**"]
27          },
28         proxy: {
29           [cfgSetting.apiType]: {
30                 target: cfgSetting.svcAddress,   //實際請求地址
31                 changeOrigin: true,
32                 ws: true,
33                 rewrite: (path) => path.replace(cfgSetting.apiType, '')
34           }
35         },
36         https: cfgSetting.svcIsHttps
37     }
38 })
View Code

      d).settings.js文件內容見第三部分的第六小節。

5.3.查看效果:啓動項目,命令:npm run dev

 

6.i18n

6.1.簡要說明:一直以來我是不建議使用i18n配置國際化,原因很簡單,語言和文化差異會使人的審美異同,衆口難調,如果使用i18n配置國際化,就很難設計出一套具備個性化的方案,最後只能做出取捨,得出一套通用沒有個性化的方案。

6.2.步驟過程

      a).安裝vue-i18n,命令:npm install vue-i18n@next

      b).在src目錄下創建locales目錄,並添加index.js,zh_cn.js,en_us.js三個文件

      c).index.js文件內容如下

 1 import { createI18n } from 'vue-i18n' //引入vue-i18n組件
 2 import zh_cn from './zh_cn'  //中文語言包
 3 import en_us from './en_us'  //英文語言包
 4  
 5 // 實例化I18n
 6 const i18n = createI18n({
 7     legacy: false,
 8     globalInjection: true,
 9     locale: "zh_cn", // 初始化配置語言
10     messages: {
11         zh_cn,
12         en_us
13     }
14 })
15 
16 export default i18n
View Code

      d).zh_cn.js文件內容如下

1 export default {
2     message: {
3         Home: '首頁',
4         About: '關於'
5     }
6 }
View Code

      e).en_us.js文件內容如下

1 export default {
2     message: {
3         Home: 'Home',
4         About: 'About'
5     }
6 }
View Code

      f).修改main.js文件,引入vue-i18n,代碼如下

1 import * as Vue from 'vue'
2 
3 import App from './App.vue'
4 import i18n from './locales/index'
5 
6 const app=Vue.createApp(App)
7 app.use(i18n)
8 app.mount('#app')
View Code

     g).修改App.vue文件,查看i18n效果

 1 <template>
 2   <img alt="Vue logo" src="@/assets/logo.png" />
 3   <a href="javascript:void(0)" @click="change('zh_cn')">中文</a> --
 4   <a href="javascript:void(0)" @click="change('en_us')">English</a>
 5   <div>{{$t("message.Home")}}---{{$t("message.About")}}</div>
 6 
 7   <router-view />
 8 </template>
 9 
10 <script>
11 import { useI18n } from 'vue-i18n'
12 
13 export default ({
14   name: "App",
15   setup() {
16     const { locale } = useI18n()
17     function change(type) {
18       locale.value = type;
19     }
20     return {
21       change
22     }
23   }
24 })
25 </script>
View Code

6.3.查看效果:啓動項目,命令:npm run dev

 

7.mock

7.1.簡要說明:前後端分離之後,使用mock模擬產生後端提供的數據是非常有必要的,即即便後端一時無法提供服務,也不影響前端的正常編程工作。

7.2.步驟過程

      a).安裝mockjs,命令:npm install mockjs --save-dev

      b).安裝vite-plugin-mock,命令:npm i vite-plugin-mock cross-env -D

      c).在 package.json 中設置環境變量

1 {
2     "scripts": {
3         "dev": "cross-env NODE_ENV=development vite",
4         "build": "vite build",
5         "serve": "vite preview"
6     }
7 }
View Code

      d).在 vite.config.js 中添加 mockjs 插件

 1 import { defineConfig } from "vite"
 2 import vue from "@vitejs/plugin-vue"
 3 import { viteMockServe } from "vite-plugin-mock"
 4 
 5 export default defineConfig({
 6     plugins: [
 7         vue(),
 8         viteMockServe({
 9             supportTs: false     //如果使用typescript開發,則需要配置supportTs爲true
10         })
11     ]
12 })
View Code

      e).在工程中根目錄創建 mock 文件夾,建立getUsers.js在其中創建需要的數據接口

 1 export default [
 2     {
 3         url: "/api/getUsers",
 4         method: "get",
 5         response: () => {
 6             return {
 7                 code: 0,
 8                 message: "ok",
 9                 data: ["張三", "李四"],
10             }
11         }
12     }
13 ]
View Code

      f).修改App.vue文件,請求接口,顯示數據

 1 <template>
 2   <img alt="Vue logo" src="./assets/logo.png" />
 3   <div v-for="(item,index) in users">
 4     {{index+1}}-{{item}}
 5   </div>
 6 </template>
 7 
 8 <script>
 9 import { onMounted, ref } from "vue";
10 import axios from "axios"
11 
12 export default defineComponent({
13   name: 'App',
14   setup() {
15     let users = ref([])
16 
17     onMounted(()=>{
18       axios.get(`/api/getUsers`).then(res=>{
19         users.value = res.data.data
20         console.log('users', users)
21       }).catch(err=>{
22         console.log(err)
23       })
24     })
25 
26     return { users }
27   }
28 })
29 </script>
View Code

7.3.查看效果:啓動項目,命令:npm run dev

 

8.sass

8.1.簡要說明:Sass是一個將腳本解析成CSS的腳本語言,即SassScript。 它擴展了 CSS3,增加了規則、變量、混入、選擇器、繼承等等特性。

8.2.步驟過程

      a).安裝sass,命令:npm i sass -D

      b).使用sass,語法:<style lang="scss"></style>

      c).特別說明:由於vite已經集成好了sass的相關loader,所以無需額外配置。

8.3.查看效果:啓動項目,命令:npm run dev

 

9.gzip

9.1.簡要說明:對打包後的文件進行壓縮,在部署到Web服務器後,可以節省帶寬資源,前提是Web服務器支持壓縮。這裏主要使用vite-plugin-compression插件實現,地址:https://github.com/anncwb/vite-plugin-compression

9.2.步驟過程

      a).安裝vite-plugin-compression插件,命令:npm i vite-plugin-compression -D

      b).修改vite.config.js文件,引入插件,代碼如下

 1 import { defineConfig } from 'vite'
 2 import vue from '@vitejs/plugin-vue'
 3 import viteCompression from 'vite-plugin-compression'
 4 import path from 'path'
 5 
 6 // https://vitejs.dev/config/
 7 export default defineConfig({
 8   plugins: [
 9     vue(),
10     viteCompression({
11       threshold: 10240,      //體積大於10kb壓縮
12       filter: /\.(js|mjs|json|css|html)$/i,
13       algorithm: 'gzip',          //壓縮算法,gzip|brotliCompress|deflate|deflateRaw
14       disable: false,
15       deleteOriginFile: false   //是否刪除源文件
16     })
17   ],
18   resolve: {
19     alias: {
20       '@': path.resolve(__dirname, 'src')
21     }
22   }
23 })
View Code

9.3.查看效果:啓動項目,命令:npm run dev

 

10.copy

10.1.簡要說明:在編程的過程中,有一些靜態資源是不需要vite進行處理的,只需要簡單拷貝到dist文件夾下即可,此時我們使用rollup-plugin-copy插件就可以實現。

10.2.步驟過程

      a).安裝rollup-plugin-copy,命令:npm install rollup-plugin-copy -D

      b).修改vite.config.js文件,引入插件,代碼如下

 1 import { defineConfig } from 'vite'
 2 import vue from '@vitejs/plugin-vue'
 3 import copy from 'rollup-plugin-copy'
 4 import path from 'path'
 5 
 6 // https://vitejs.dev/config/
 7 export default defineConfig({
 8   plugins: [
 9     vue(),
10     copy({
11       targets: [
12         { src: 'src/static', dest: 'dist' }, //執行拷貝
13       ],
14       hook: 'writeBundle' // notice here
15     })
16   ],
17   resolve: {
18     alias: {
19       '@': path.resolve(__dirname, 'src')
20     }
21   }
22 })
View Code

10.3.查看效果:啓動項目,命令:npm run dev

 

 

三、配置信息

1.vite.config.js

  1 import { defineConfig } from 'vite'
  2 import vue from '@vitejs/plugin-vue'
  3 import { viteMockServe } from "vite-plugin-mock"
  4 import viteCompression from 'vite-plugin-compression'
  5 import copy from 'rollup-plugin-copy'
  6 import path from 'path'
  7 import cfgSetting from './src/configs/settings'
  8 
  9 // https://vitejs.dev/config/
 10 export default defineConfig({
 11   base: './',
 12   publicDir: "public",      //靜態資源服務的文件夾
 13   logLevel: "info",         //控制檯輸出的級別 info 、warn、error、silent
 14   clearScreen: true,         //設爲false 可以避免 vite 清屏而錯過在終端中打印某些關鍵信息
 15   build: {
 16     //瀏覽器兼容性  "esnext"|"modules"
 17     target: "modules",
 18     //指定輸出路徑
 19     outDir: "dist",
 20     //生成靜態資源的存放路徑
 21     assetsDir: "assets",
 22     //小於此閾值的導入或引用資源將內聯爲 base64 編碼,以避免額外的 http 請求。設置爲 0 可以完全禁用此項
 23     assetsInlineLimit: 4096,
 24     //啓用/禁用 CSS 代碼拆分
 25     cssCodeSplit: true,
 26     //構建後是否生成 source map 文件
 27     sourcemap: false,
 28     //自定義底層的 Rollup 打包配置
 29     rollupOptions: {
 30       output: {
 31       }
 32     },
 33     //當設置爲 true,構建後將會生成 manifest.json 文件
 34     manifest: false,
 35     /*
 36       設置爲 false 可以禁用最小化混淆,或是用來指定使用哪種混淆器
 37       boolean | 'terser' | 'esbuild'
 38       terser 構建後文件體積更小
 39     */ 
 40     minify: 'terser',
 41     //傳遞給 Terser 的更多 minify 選項。
 42     terserOptions: {
 43       compress:{
 44         drop_console: true,
 45         drop_debugger: true
 46       }
 47     },
 48     //設置爲 false 來禁用將構建後的文件寫入磁盤
 49     write: true,
 50     //默認情況下,若 outDir 在 root 目錄下,則 Vite 會在構建時清空該目錄。
 51     emptyOutDir: true,
 52     //啓用/禁用 brotli 壓縮大小報告
 53     brotliSize: true,
 54     //chunk 大小警告的限制
 55     chunkSizeWarningLimit: 500
 56   },
 57   plugins: [
 58     vue(),
 59     viteMockServe({
 60       supportTs: false     //如果使用typescript開發,則需要配置supportTs爲true
 61     }),
 62     viteCompression({
 63       threshold: 10240,      //體積大於10kb壓縮
 64       filter: /\.(js|mjs|json|css|html)$/i,
 65       algorithm: 'gzip',          //壓縮算法,gzip|brotliCompress|deflate|deflateRaw
 66       disable: false,
 67       deleteOriginFile: false   //是否刪除源文件
 68     }),
 69     copy({
 70       targets: [
 71         { src: 'src/static', dest: 'dist' }, //執行拷貝
 72       ],
 73       hook: 'writeBundle' // notice here
 74     })
 75   ],
 76   resolve: {
 77     alias: {
 78       '@': path.resolve(__dirname, 'src')
 79     }
 80   },
 81   server: {
 82     host: cfgSetting.spaAddress,
 83     port: cfgSetting.spaPort,
 84     strictPort: false,              //設爲true時端口被佔用則直接退出,不會嘗試下一個可用端口
 85     cors: true,                     //爲開發服務器配置CORS, 默認啓用並允許任何源
 86     open: true,                     //服務啓動時自動在瀏覽器中打開應用
 87     hmr: false,                     //禁用或配置 HMR 連接
 88     //傳遞給 chockidar 的文件系統監視器選項
 89     watch: {
 90       ignored:["!**/node_modules/your-package-name/**"]
 91      },
 92     proxy: {
 93       [cfgSetting.apiType]: {
 94             target: cfgSetting.svcAddress,   //實際請求地址
 95             changeOrigin: true,
 96             ws: true,
 97             rewrite: (path) => path.replace(cfgSetting.apiType, '')
 98       }
 99     },
100     https: cfgSetting.svcIsHttps
101   }
102 })
View Code

2.vue-router/index.js

 1 import * as vueRouter from 'vue-router';
 2 
 3 const routes = [
 4     { 
 5         path: "/", 
 6         redirect: "/home" 
 7     },
 8     { 
 9         path: '/home', 
10         name: 'Home', 
11         component: () => import("@/views/home/index.vue") 
12     }
13 ]
14 
15 const router = vueRouter.createRouter({
16     history: vueRouter.createWebHistory(),
17     routes: routes
18 })
19 
20 export default router
View Code

3.vuex/index.js

1 import Vuex from 'vuex'
2 import getters from './getters'
3 
4 const store = Vuex.createStore({
5     modules:{ },
6     getters
7 })
8 
9 export default store
View Code

4.i18n/index.js

 1 import { createI18n } from 'vue-i18n' //引入vue-i18n組件
 2 import zh_cn from './zh_cn'  //中文語言包
 3 import en_us from './en_us'  //英文語言包
 4  
 5 // 實例化I18n
 6 const i18n = createI18n({
 7     legacy: false,
 8     globalInjection: true,
 9     locale: "zh_cn", // 初始化配置語言
10     messages: {
11         zh_cn,
12         en_us
13     }
14 })
15 
16 export default i18n
View Code

5.main.js

 1 import * as Vue from 'vue'
 2 
 3 import App from './App.vue'
 4 import router from './router/index'
 5 import store from './store/index'
 6 import i18n from './locales/index'
 7 import ElementPlus from 'element-plus'
 8 import 'element-plus/theme-chalk/index.css'
 9 import zhCn from 'element-plus/es/locale/lang/zh-cn'
10 
11 const app=Vue.createApp(App)
12 app.use(store)
13 app.use(router)
14 app.use(i18n)
15 app.use(ElementPlus,{locale:zhCn})
16 app.mount('#app')
View Code

6.configs/settings.js

1 module.exports = {
2     apiType:'/devApi',
3     spaAddress:'127.0.0.1',
4     spaPort: 9000,
5     svcAddress:'http://www.weather.com.cn',
6     svcIsHttps: false
7 }
View Code

 

四、其他信息

1.目錄結構

 

 

2.兼容性

2.1.由於vite利用了瀏覽器導模塊的能力,所以主流瀏覽器的最低版本如下:

           a).Chrome >=61

           b).Firefox >=60

           c).Safari >=11

           d).Edge >=16

      那些古老的瀏覽器(如IE)就不支持了。

2.2.針對兔民的懷舊情懷,官方也提供了低瀏覽器版本的解決方案,即使用插件@vitejs/plugin-legacy(https://github.com/vitejs/vite/tree/main/packages/plugin-legacy),使用它之後vite打包出來的程序就可以在低版本瀏覽器中運行。原理就是利用@babel/preset-env進行轉換,自然打包效率就會大幅度降低,因此需要做取捨。

3.代碼規範

爲了使代碼具備更好的可讀性和可維護性,以及維護團隊成員良好的協作效率,你可以在工程中配置代碼規範格式管理約束,具體使用哪種工具和風格自我選擇即可。

4.上述內容中完整的App.vue文件內容

 1 <template>
 2   <img alt="Vue logo" src="@/assets/logo.png" />
 3   <a href="javascript:void(0)" @click="change('zh_cn')">中文</a> --
 4   <a href="javascript:void(0)" @click="change('en_us')">English</a>
 5   <div>{{$t("message.Home")}}---{{$t("message.About")}}</div>
 6 
 7   <div>
 8     {{weatherinfo.city}}
 9     {{weatherinfo.WD}}
10     {{weatherinfo.WS}}
11   </div>
12 
13   <div v-for="(item,index) in users">
14     {{index+1}}-{{item}}
15   </div>
16 
17   <el-form :inline="true" :model="formInline" class="demo-form-inline">
18     <el-form-item label="審批人">
19       <el-input v-model="formInline.user" placeholder="審批人"></el-input>
20     </el-form-item>
21     <el-form-item label="活動區域">
22       <el-select v-model="formInline.region" placeholder="活動區域">
23         <el-option label="區域一" value="shanghai"></el-option>
24         <el-option label="區域二" value="beijing"></el-option>
25       </el-select>
26     </el-form-item>
27     <el-form-item>
28       <el-button type="primary" @click="onSubmit">查詢</el-button>
29     </el-form-item>
30   </el-form>
31 
32   <router-view />
33 </template>
34 
35 <script>
36 import { useI18n } from 'vue-i18n'
37 import { onMounted, reactive, ref } from "vue";
38 import axios from "axios"
39 
40 export default ({
41   name: "App",
42   setup() {
43     const { locale } = useI18n()
44     function change(type) {
45       locale.value = type;
46     }
47 
48     let weatherinfo = reactive({})
49     onMounted(()=>{
50       axios.get(`/devApi/data/sk/101010100.html`).then(res=>{
51         Object.assign(weatherinfo, res.data.weatherinfo)
52       }).catch(err=>{
53         console.log(err)
54       })
55     })
56 
57     let users = ref([])
58     onMounted(()=>{
59       axios.get(`/api/getUsers`).then(res=>{
60         users.value = res.data.data
61         console.log('users', users)
62       }).catch(err=>{
63         console.log(err)
64       })
65     })
66 
67     return {
68       change,
69       weatherinfo,
70       users
71     }
72   },
73   data() {
74     return {
75       formInline: {
76         user: "",
77         region: "",
78       }
79     }
80   },
81   methods: {
82     onSubmit() {
83       console.log("submit!")
84     }
85   }
86 })
87 </script>
View Code

 

五、參考信息

1.https://www.cnblogs.com/zsg88/p/15652011.html

2.https://juejin.cn/post/6989475484551610381

3.https://juejin.cn/post/6973288527802925092

4.https://juejin.cn/post/6946007023951544357

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章