亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

一個(gè)基于vue3+ts+vite項(xiàng)目搭建初探

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

前言

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

下面記錄一下怎么使用Vue3 + ts + vite 從0開始搭建一個(gè)項(xiàng)目

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

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

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

image-20220509091913314.png

使用Vite快捷搭建

使用npm

npm init @vitejs/app

使用yarn

yarn create @vitejs/app

按照提示完成項(xiàng)目初始化即可

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

安裝依賴

npm install 或者 yarn install

啟動(dòng)項(xiàng)目

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ù)器上頁(yè)面空白的問(wèn)題(主要是65版本不兼容 try catch )
          cssTarget:'chrome65', // 兼容低版本瀏覽器上樣式問(wèn)題
          assetsDir: './assets',  // 打包配置路徑
          rollupOptions: { 
            input: {    // 主要用于配置多頁(yè)面
              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)然在配置路由的時(shí)候也可以提取側(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 配置文件的時(shí)候已經(jīng)提到怎么按需引入element了

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

因?yàn)閑lement plus 默認(rèn)是英語(yǔ) 所以如果在項(xiàng)目中需要使用的是中文的話,可參加以下配置

在 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')

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

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

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

集成axios

  • 安裝axios

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

    import Axios from "axios"
    import { ElMessage } from "element-plus"
    
    const BASE_URL = ''; //請(qǐng)求接口url 如果不配置 則默認(rèn)訪問(wèn)鏈接地址
    const TIME_OUT = ''; // 接口超時(shí)時(shí)間
    const instance = Axios.create({
    	baseURL:BASE_URL,
    	TIME_OUT:TIME_OUT
    })
    
    // 可以添加一個(gè)axios的全局配置
    instance.defaults.headers.post = {
    		"Content-Type":'application/x-www-form-urlencoded'
    }
    
    // 添加請(qǐng)求攔截器
    instance.interceptors.request.use((config) => {
            // 可以在此處添加一些共有的請(qǐng)求攔截
            ...
    	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下新建一個(gè)API的文件夾,在文件夾下添加user.ts 文件

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

    在需要使用這個(gè)接口的頁(yè)面進(jìn)行引入即可 例如在login.vue中

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

集成Sass

  • 安裝sass

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

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

Vue3 使用

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

  • 生命周期函數(shù)

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

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

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

    通常使用reactive來(lái)賦予對(duì)象響應(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為一個(gè)空的字符串
    		
    	const handleClick = () => {
    		name.value = 'lemon' // 需要注意的是修改值時(shí),不適用this
    	}
    	export default defineComponent({
                 setup(){		
                //
                    return {
                        name  // 返回name
                    }
                 }
    	 })
    </script>

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

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

    在vue2中可以使用options 來(lái)初始化數(shù)據(jù),vue3沒(méi)有這個(gè)屬性

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

    // vue 中有以下兩個(gè)方法
    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 還可用于使用一個(gè)v-model 雙向數(shù)據(jù)綁定的功能(例如: 頁(yè)面彈框顯示與關(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ù)第一個(gè)參數(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 處也可以添加一個(gè)方法 () => props.name
                watch(name,()=>{
                    // 可添加異步請(qǐng)求
                })
    	}
    })

總結(jié)

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

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

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

相關(guān)文章

最新評(píng)論