萌新的VUE3搭建教程

96 阅读7分钟

注意注意

本教程仅针对VUE3+VITE的萌新初始化搭建教程,并不包含知识点

废话不多说,进入正题

第一步:跑起来

万世开头难,VUE3的教程已经可以说很简单明了了,那么,直接跟着文档先敲了再说,首先找个存放项目的地方。接着,打开命令行。

npm init vue@latest

好吧,不配图了。

Need to install the following packages:
    create-vue@latest
Ok to proceed? (y)

应该不需要解释什么吧?(好吧,我承认,我是文盲,我需要翻译)

简单来说,就是需要安装create-vue@latest的包,询问你是否要继续,那肯定要继续的,所以输入Y,回车。

等待完成之后,就进入了熟悉的界面了。

✔ Project name: … <your-project-name>  // 项目名称
✔ Add TypeScript? … No / Yes  // 是否使用TS
✔ Add JSX Support? … No / Yes  // 是否加入JSX支持
✔ Add Vue Router for Single Page Application development? … No / Yes // 是否添加路由
✔ Add Pinia for state management? … No / Yes  // 是否使用Pinia (新一代的VUEX,感兴趣的小伙伴可以了解一下)
✔ Add Vitest for Unit testing? … No / Yes // 是否添加单元测试
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes  // 是否添加Vitest来进行单元测试
✔ Add ESLint for code quality? … No / Yes // 老朋友,ESLint

Scaffolding project in ./<your-project-name>... 
Done.

完成之后,便会有提示

  cd <your-project-name>
  npm install
  npm run dev

无脑按照流程走咯,cd进入项目,npm install(简写为npm i 功能是一样的)

重头戏来了

npm run dev

此时第一次接触的小伙伴应该会和我有同样的感受吧,我的天,真快?这就是传说中的VITE?

第二步:删删删

项目跑起来之后,并没有帮我们自动打开浏览器,那么手动打开命令行提示的内容

 VITE v3.1.0  ready in 437 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose

当然,我这里的端口号是5173,小伙伴们别搞错了(难道5173打广告了?)

打开页面之后就是很基础的内容了对吧,想研究研究的小伙伴可自行研究,我反正是不看,我要开始删了

当然,还缺少一步,我需要先把项目拖到编辑器里。这样方便。

首先看下目录结构,好吧,也没什么好看的,能看的也就src目录了。

展开src后,文件夹的目录是这样的

assets
components
router(上面选项的Router我选择了Yes,当然其他选项都是No,毕竟我是萌新)
views

那就,,,开删吧?

assets下的内容全删完,毕竟一会我要创建自己的公用样式

components下的内容全删完,组件还是要自己写的

router下的内容全删完,当然,这是不可能的,这个先不动,一会再说

views下的内容全删完,个人习惯

此时,在views目录下,创建一个

template.vue

完全个人习惯哈,我喜欢创建一个模板,新建页面的时候直接复制粘贴,当前也推荐使用代码块的方式,个人习惯,不多说

内容呢,也很简单

<template>
    <div class="template_box"></div>
</template>

<script setup></script>

<style scoped>
    .template_box{

    }
</style>

当然,此时还不行,还需要一个首页嘛对吧?在views目录下,创建一个

index.vue

内容同上。可以随便加点内容

<template>
	<div class="index">
        <h1>Hello</h1>
        <p>世界(嗯,对,英文不会拼)</p>
    </div>
</template>
<script setup></script>

<style scoped>
    .index{

    }
</style>

好了,此时回到我们的router目录,打开里面的index.js

import {
    createRouter,
    createWebHistory
} from 'vue-router'
import HomeView from '../views/HomeView.vue' // 这句话没用,删了

const router = createRouter({
    history: createWebHistory(
        import.meta.env.BASE_URL),
    routes: [
        // -----------这里面的都没用-----------
        {
            path: '/',
            name: 'home',
            component: HomeView
        },
        {
            path: '/about',
            name: 'about',
            // route level code-splitting
            // this generates a separate chunk (About.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () => import('../views/AboutView.vue')
        }
        // ---------------------------------
        // 刚才我们创建了一个index.vue,所以我们需要加到路由里面
        // 添加一个
        {
            path: '/index',
            name: '首页',
            component: () => import('../views/index.vue')
        }
    ]
})

export default router

此时,还没有删完

打开src下的

App.vue

<script setup>
import { RouterLink, RouterView } from 'vue-router';
import HelloWorld from './components/HelloWorld.vue'; // 删了删了删了
</script>

<template>
        // 删了删了删了
	<header>
		<img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

		<div class="wrapper">
			<HelloWorld msg="You did it!" />

			<nav>
				<RouterLink to="/">Home</RouterLink>
				<RouterLink to="/about">About</RouterLink>
			</nav>
		</div>
	</header>
        // ---------------
	<RouterView />
</template>

<style scoped>
// 删了删了删了
header {
	line-height: 1.5;
	max-height: 100vh;
}

.logo {
	display: block;
	margin: 0 auto 2rem;
}

nav {
	width: 100%;
	font-size: 12px;
	text-align: center;
	margin-top: 2rem;
}

nav a.router-link-exact-active {
	color: var(--color-text);
}

nav a.router-link-exact-active:hover {
	background-color: transparent;
}

nav a {
	display: inline-block;
	padding: 0 1rem;
	border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
	border: 0;
}

@media (min-width: 1024px) {
	header {
		display: flex;
		place-items: center;
		padding-right: calc(var(--section-gap) / 2);
	}

	.logo {
		margin: 0 2rem 0 0;
	}

	header .wrapper {
		display: flex;
		place-items: flex-start;
		flex-wrap: wrap;
	}

	nav {
		text-align: left;
		margin-left: -1rem;
		font-size: 1rem;

		padding: 1rem 0;
		margin-top: 1rem;
	}
}
// --------------------------
</style>

删完之后,就得到了一个干净的文件

<script setup>
import { RouterLink, RouterView } from 'vue-router';
</script>

<template>
	<RouterView />
</template>

<style scoped></style>

当然,现在肯定还是报错的

打开src下的main.js

import './assets/main.css' 把这句话删了(不知道怎么备注了)

OK。此时,干净的项目已经完成。页面上也出现了内容。

你以为这就完了,当然,接下来才是重点

第三步:先把路由搞一下

此处省略一下新建页面(center.vue)的操作

新建完成之后,路由当然也添加过了吧?当然,路由的拦截在项目中也是必不可少的,那么现在我们的路由文件应该是这个样子的。

const router = createRouter({
    history: createWebHistory(
        import.meta.env.BASE_URL),
    routes: [{
        path: '/',
        name: '首页',
        component: () => import('../views/index.vue'),
        meta: {
            login: false
        }
    }, {
        path: '/center',
        name: '个人中心',
        component: () => import('../views/center.vue'),
        meta: {
            login: true
        }
    }, ]
})

其中meta是自定义的属性,习惯使用login字段来校验这个页面是否需要登录(想用什么字段用什么字段)

加了这个属性当然没用,逻辑还是需要自己处理嘛,紧接着在下面增加路由拦截

import {
    createRouter,
    createWebHistory
} from 'vue-router'
import store from 'store'

const router = createRouter({
    history: createWebHistory(
        import.meta.env.BASE_URL),
    routes: [{
        path: '/',
        name: '首页',
        component: () => import('../views/index.vue'),
        meta: {
            login: false
        }
    }, {
        path: '/center',
        name: '个人中心',
        component: () => import('../views/center.vue'),
        meta: {
            login: true
        }
    }, ]
})

router.beforeEach((to, from, next) => {
    if (to.meta.login && !store.get('token')) {
        // 自己的逻辑
        return
    }
    next()
})


export default router

这个store本不想解释,还是解释一下吧,store都知道干嘛的吧?当然你可以用vuex,或cookie等,仅是获取一个判断用户有没有登录的字段的作用。

好吧好吧,多说一句,回到index.vue中,写个跳转不过分吧?

<template>
    <div class="index">
        <h1>Hello</h1>
        <p>世界</p>

        <button @click="jump('/center?code=123')">to center</button>
    </div>
</template>
<script setup>
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

let jump = (url) => {
	proxy.$router.push(url);
};
</script>

<style scoped>
.index {
}
</style>

简单的写个跳转,因为没有Vue3中没有this了。所以Vue2版本的this.$router.push也没办法使用了,那就换下咯,依旧是在main.js中,定义一下全局变量(不会的看文档)

// main.js
import {
    createApp
} from 'vue'
import App from './App.vue'
import router from './router'
import {
    useRoute
} from 'vue-router'
import store from 'store'


const app = createApp(App)

// Vue3中挂载全局的方法
app.config.globalProperties.$router = router
app.config.globalProperties.$route = useRoute
app.config.globalProperties.$store = store
app.use(router)


app.mount('#app')

在vue文件中取用的时候,方式也发生了变化

// index.vue
// 这两句话是重点,不过多的说
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

let jump = (url) => {
	proxy.$router.push(url);
};

那么同理,我们在跳转的时候,看到带了一个参数,怎么去拿这个参数呢?

我们在main.js中还有一个全局变量

import { useRoute } from 'vue-router'

app.config.globalProperties.$route = useRoute

那么我们在center页面中

<script setup>
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

// 打印一下你就什么都知道咯
console.log(proxy.$router);
</script>

路由到此结束

第四步:公用Less

我用Less,所以就拿Less来说

我们肯定会用到一些公用的样式,而且会定义一些全局变量来方便使用,具体使用不过多的说,直接上代码吧。

首先肯定要装LessLess-loader

npm i less less-loader --save-dev

此时呢,有个重要的事情,我们还需要安装style-resources-loader,常规来说我们肯定是

npm install style-resources-loader

但,换种方式

vue add style-resources-loader

我们使用vue add的方式来添加,它会帮助我们自动安装好所需的依赖,当然就是vue-cli-plugin-style-resources-loader,好吧,这一步其实还会多生成一个vue.config.js,把这个文件删了就好

在安装过程中,注意命令行会有段选择

? CSS Pre-processor?
  SCSS
  SASS
  Stylus
> Less

会让你选择你要使用的Css预编译器,我当然选择Less了

成功之后,在.vue文件中,style标签上加入lang="less",我们就已经可以使用了

<style scoped lang="less">
.index {
    background-color: black;
    
    h1{
        color: white;
    }
}
</style>

当然,这并不符合我们的要求,我们要做的是公用的样式

assets中新建css目录,创建一个common.less(括弧:目录及名字,你随意)

简单一点,在common.less中先定义一个变量

@color: #fff;

当然,其他页面肯定是用不了的。还需要配置的嘛,怎么可能这么简单

此时如果你尝试过,那么你可能和我一样,百度了半天,答案都是在vue.config中配置,当然,vue2的确是这样配置的,可我们的Vue3用的是vite呀,当然不能这么配置了

其实也很简单,打开vite.config.js

export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    // 只需要这段
    css: {
        preprocessorOptions: {
            less: {
                modifyVars: {
                    hack:`true;@import(reference)"${path.resolve("src/assets/css/common.less")}";`,
                },
                javascriptEnabled: true,
            },
        },
    },
    // ----------------
})

当然,里面用到了path,我们还需要引入一下,在vite.config.js的最上面,加一句就好了

const path = require("path");

此时,重启项目,测试下变量是否可以使用了(当然可以使用了)

第五步:封装公共的api

写不动了,回头更新吧

小结

至于公用的方法之类的就不在多说了,参考router挂载全局,页面调用就行了

感谢各位大佬能看到此处,全文没有配图,没有涵盖技术点,因为,,,感觉这些也没什么技术点,会用就行。这种东西搭建出来一套就足够了。有些不完善的,或者需要改进的,也希望各位大佬不吝啬,给弟弟提出一些改进意见,再次谢谢啦。