欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一個基于vue3+ts+vite項目搭建初探

 更新時間:2022年05月23日 09:41:43   作者:lemonChen  
當(dāng)市面上主流的組件庫不能滿足我們業(yè)務(wù)需求的時候,那么我們就有必要開發(fā)一套屬于自己團隊的組件庫,下面這篇文章主要給大家介紹了一個基于vue3+ts+vite項目搭建的相關(guān)資料,需要的朋友可以參考下

前言

基于Vue3已經(jīng)成為默認(rèn)版本,目前的項目暫時還沒有使用過vue3開發(fā)和最近有一個全新的新項目的基礎(chǔ)下,使用vue3開發(fā)項目,必然是未來的一個趨勢

下面記錄一下怎么使用Vue3 + ts + vite 從0開始搭建一個項目

環(huán)境準(zhǔn)備

Nodejs 版本>=12  使用node -v 查看 node版本

或者將Nodejs升級到最新的穩(wěn)定版本 npm install -g n  sudo n stable 

image-20220509091913314.png

使用Vite快捷搭建

使用npm

npm init @vitejs/app

使用yarn

yarn create @vitejs/app

按照提示完成項目初始化即可

初始化項目以后可以看到項目的結(jié)構(gòu)如上圖

安裝依賴

npm install 或者 yarn install

啟動項目

npm run dev 或者 yarn dev

修改vite配置文件

找到根目錄vite.config.ts文件打開

  • 添加別名,配置@指向src

     import { defineConfig } from 'vite';
     import vue from '@vitejs/plugin-vue';
     import { resolve } from "path";
     const pathResolve = (dir: string) => resolve(__dirname, dir);
     
     export default defineConfig({
        plugins:[
          vue()
        ],
        resolve: {
          alias: {
            "@": pathResolve("./src"),   // 別名
          }
        }
     })
  • 按需導(dǎo)入element ui

    首先需要安裝unplugin-vue-componentsunplugin-auto-import這兩款插件

    npm install -D unplugin-vue-components unplugin-auto-import

    然后在vite.config.ts中添加以下配置

      import AutoImport from 'unplugin-auto-import/vite';
      import Components from 'unplugin-vue-components/vite';
      import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
      
      export default defineConfig({
        plugins:[
          AutoImport({
            resolvers: [ElementPlusResolver()]
          }),
          Components({
            resolvers: [ElementPlusResolver()]
          })
        ]
      })
  • 打包配置

    export default defineConfig({
        build: {
          target: 'es2015',  //主要用于兼容低版本瀏覽器 可以解決chrome65版本打包發(fā)布到服務(wù)器上頁面空白的問題(主要是65版本不兼容 try catch )
          cssTarget:'chrome65', // 兼容低版本瀏覽器上樣式問題
          assetsDir: './assets',  // 打包配置路徑
          rollupOptions: { 
            input: {    // 主要用于配置多頁面
              platForm: resolve(__dirname, 'platform.html'),
              merchant: resolve(__dirname, 'merchant.html')
            }
          }
        }
    })

集成路由

  • 安裝vue-router

    npm i vue-router@4
  • 在src目錄下面添加router文件夾 然后在文件夾下添加index.ts文件

    import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
    
    const routes: Array<RouteRecordRaw> = [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/home.vue')
      },
      { path: '/', redirect: { name: 'Home' } }
    ]
    
    const router = createRouter({
      history: createWebHashHistory(),
      routes
    })
    
    export default router

    當(dāng)然在配置路由的時候也可以提取側(cè)邊欄組件作為公共的組件,配置方法跟vue2 集成路由方法一致,添加children屬性

  • 在main.ts中掛載

    import { createApp } from 'vue'
    import App from '@/App.vue'
    import router from '@/router/index'
    
    const app = createApp(App)
    
    app.use(router).mount('#app')

集成Vuex

  • 安裝 vuex@next

    npm i vuex@next
  • 在src文件夾下面添加store文件夾,然后在文件夾下面添加index.ts 文件

    import { createStore } from "vuex"
     
    export default createStore({
    	state:{
               count:0
    	},
    	mutations:{
                setCount(state,count){
                    state.count = count
                }
    	},
    	actions:{
                getCount({ commit }){
                    commit('setCount',xxx)
                }
    	}
    })
  • 在main.ts 中掛載

    import { createApp } from 'vue'
    import App from '@/App.vue'
    import router from '@/router/index'
    import store from '@/store/index'
    
    const app = createApp(App)
    
    app.use(router).use(store).mount('#app')

添加element ui

上面講解vite 配置文件的時候已經(jīng)提到怎么按需引入element了

現(xiàn)在只需要在main.ts文件中掛載element 即可

因為element plus 默認(rèn)是英語 所以如果在項目中需要使用的是中文的話,可參加以下配置

在 main.ts 文件中添加

import { createApp } from 'vue'
import App from '@/App.vue'
import ElementPlus from "element-plus"

import zhCn from 'element-plus/es/locale/lang/zh-cn';
import router from '@/router/index'
import store from '@/store/index'

const app = createApp(App)

app.use(ElementPlus,{locale:zhCn})

app.use(router).use(store).mount('#app')

還有一點需要注意的是,如果您使用 unplugin-element-plus 并且只使用組件 API,您需要手動導(dǎo)入樣式

如果系統(tǒng)中會經(jīng)常用到ElMessage、ElMessageBox 等api,可以main.ts 文件中添加以下樣式,不然會導(dǎo)致樣式問題

import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'

集成axios

  • 安裝axios

    npm i axios
  • 添加全局的請求工具 在src下新建一個utils文件夾,文件夾下面添加一個http.ts文件

    import Axios from "axios"
    import { ElMessage } from "element-plus"
    
    const BASE_URL = ''; //請求接口url 如果不配置 則默認(rèn)訪問鏈接地址
    const TIME_OUT = ''; // 接口超時時間
    const instance = Axios.create({
    	baseURL:BASE_URL,
    	TIME_OUT:TIME_OUT
    })
    
    // 可以添加一個axios的全局配置
    instance.defaults.headers.post = {
    		"Content-Type":'application/x-www-form-urlencoded'
    }
    
    // 添加請求攔截器
    instance.interceptors.request.use((config) => {
            // 可以在此處添加一些共有的請求攔截
            ...
    	return config
    },(error) => {
    	return Promise.reject(error);
    })
    
    // 添加響應(yīng)攔截器
    instance.interceptors.response.use((response)=>{
    	const res = response.data;
    	// 在此處添加一些響應(yīng)攔截
    	 ...
    },(error)=>{
    	return Promise.reject(error);
    })
    
    export default instance;
  • 使用axios 在src下新建一個API的文件夾,在文件夾下添加user.ts 文件

    import $http from '@/utils/http';
    
    // 添加用戶登錄請求 data如果約定好可以添加ts 接口類型
    export const userLogin = (data:any) => {
    	return $http({
                   url:'xxx',
                   method:'post',
                   data
    	})
    }

    在需要使用這個接口的頁面進行引入即可 例如在login.vue中

    <script lang="ts">
    	import { userLogin } from "@/api/user"
    </script> 

集成Sass

  • 安裝sass

    npm i sass -D
  • 使用 在.vue 文件中

    <style lang="scss">
    	...  // 此處可以用sass語法編寫
    </style>

Vue3 使用

在vue3中去除了filters用法,如果需要用到,可以自行實現(xiàn)

  • 生命周期函數(shù)

    <script lang="ts">
    	 import {
    	 	onMounted,
    	 	defineComponent
    	 } from "vue";
    	 
    	 export default defineComponent({
    	 	setup(){
                    // 添加一個方法 
                        const getList = () => {
                            ...
                        }
                        onMounted(getList)
    	 			
                        return {
                            getList  // 如果在template中使用到這個方法,需要返回
                        }
                 }
    	 })
    </script>
  • 響應(yīng)式數(shù)據(jù)

    在vue3中可以通過ref 和 reactive來創(chuàng)建一個響應(yīng)式數(shù)據(jù),如下:

    通常使用 ref 來將一個原始數(shù)據(jù)類型轉(zhuǎn)換成帶有響應(yīng)式特性的數(shù)據(jù)類型(也可以用來初始化對象類型)

    通常使用reactive來賦予對象響應(yīng)性特性

    <template>
    	<div>
            <p> hello,{{ name }} </p>
            <el-button @click='handleClick'></el-button>
    	</div>
    </template>
    <script lang='ts'>
    	import { ref , reactive,defineComponent} from "vue";
    		
    	const name = ref(''); // 初始化name為一個空的字符串
    		
    	const handleClick = () => {
    		name.value = 'lemon' // 需要注意的是修改值時,不適用this
    	}
    	export default defineComponent({
                 setup(){		
                //
                    return {
                        name  // 返回name
                    }
                 }
    	 })
    </script>

    用ref創(chuàng)建響應(yīng)式數(shù)據(jù)時 不需要使用this ,但是要使用name.value 表示數(shù)據(jù)的值

  • 初始化數(shù)據(jù)

    在vue2中可以使用options 來初始化數(shù)據(jù),vue3沒有這個屬性

    // 首先可以定義一個方法 返回初始化數(shù)據(jù)
    const formData = () => {
    	return {
                userName:'',
                password:''
    	}
    }
    
    // 初始化頁面展示數(shù)據(jù)
    const form = reactive(formData())
    
    // 重置數(shù)據(jù)為初始化狀態(tài)
    Object.assign(form,formData())
  • 路由使用

    // vue 中有以下兩個方法
    import { useRoute, useRouter} from "vue";
    
    const route = userRoute(); // route 表示的是當(dāng)前路由
    
    export default defineComponent({
    	 setup(){
    	 		
                    const router = useRouter() // 用于路由跳轉(zhuǎn)
            
                    return {}
    	 }
    })

    useRouter() 一定要放在setup方法里面最上方位置 不然數(shù)值為undefined

  • 引入組件

    引入組件的方式跟vue2 一致

    import layout from "@/layout/index"
    
    export default defineComponent({
    	components:{
    		layout
    	}
    })
  • 使用vuex

    vue3 提供了 useStore 方法

    import { useStore } from "vue";
    
    export default defineComponent({
    	 setup(){
                    const store = useStore() // 
            
                    return {}
    	 }
    })
  • computed 和 props用法

    vue3 提供了computed方法

     // 基本用法
    import { computed } from 'vue';
    export default defineComponent({
    	setup(){
    	   // 
            const name = computed({
                  return XXX;
            })
    			
            return {
    		name
            }
        }
   })
computed 還可用于使用一個v-model 雙向數(shù)據(jù)綁定的功能(例如: 頁面彈框顯示與關(guān)閉)

需要跟props , emit 一起使用
    import { computed } from 'vue';
    export default defineComponent({
    	props:{
            modelValue:{
    		type:Boolean,
    		default:false
            }
    	}
    	emits: ['update:modelValue'],
    	setup(props,{ emit }){
    			// 
    		const dialogVisible = computed({
                    get:() => props.modelValue, // setup 函數(shù)第一個參數(shù)是props
                    set:(newVal) => {
    			emit("update:modelValue",newVal)
                    }
    		})
    			
    		return {
                    dialogVisible
    		}
    	}
    })

在其他地方引用該組件的使用 v-model 即可

  • watch 監(jiān)聽使用

    vue3 提供了 watch 方法

    import { watch, ref } from "vue"
    
    const name = ref('')
    export default defineComponent({
    	
    	setup(props){
    		
                // name 處也可以添加一個方法 () => props.name
                watch(name,()=>{
                    // 可添加異步請求
                })
    	}
    })

總結(jié)

基于以上,一個基于Vue3 + element + vite 的基本后臺管理系統(tǒng),大致是可以成型的,另外還有一些比如配置eslint 代碼規(guī)范, 可以自己自行添加,還有vue3 其他一些進階的用法,會用其他的文章來進行講述。

希望以上的內(nèi)容 ,對于沒有接觸過vue3 開發(fā)的人會有所幫助

到此這篇關(guān)于一個基于vue3+ts+vite項目搭建的文章就介紹到這了,更多相關(guān)vue3+ts+vite項目搭建內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論