创建一个 Vue.js 项目,通常使用 Vue CLI(命令行界面)。
以下是一个基本的步骤指南和示例代码:
1、安装 Vue CLI
如果你还没有安装 Vue CLI,可以通过 npm 或 yarn 来安装:
npm install -g @vue/cli
2、创建一个新的 Vue 项目
使用 Vue CLI 创建一个新的项目:(提示:项目名称不可用大写)
vue create myhelloworld
然后再选择 vue版本,当前选择版本 :vue 3 ;
3、进入项目目录并启动开发服务器
进入项目目录
cd myhelloworld
启动开发服务器
npm run serve
现在,你的 Vue.js 项目应该在Local: http://localhost:8080/
vue.js项目创建完成
vue.js 项目 开始搭建
1、创建 .vue 文件
首先,在 src/components 文件夹(或者你的项目中存放组件的文件夹)下创建一个新的 .vue 文件。例如,你可以创建一个名为 MyNewPage.vue 的文件。
2、编写 .vue 文件内容
在 MyNewPage.vue 文件中,你需要编写 vue 组件的模板、脚本和样式。
<template>
<div>
<h1>这是新的页面</h1>
<p>这里可以添加更多的内容222...</p>
</div>
</template>
<script>
export default {
name: 'MyNewPage',
// 可以在这里添加数据、方法等
}
</script>
<style scoped>
/* scoped 样式只作用于当前组件 */
h1 {
color: blue;
}
</style>
3、在路由中添加页面
3.1 安装 vue router(新建终端,进入当前项目)
npm install vue-router@4
3.2 创建 Vue Router 实例
项目使用了 Vue Router,需要在路由配置文件中添加新的路由来映射到你的新页面。
在 src 目录下创建一个 router 文件夹,并在其中创建一个 index.js 文件来配置你的路由。
src/router/index.js:
import { createRouter, createWebHistory } from 'vue-router'
import HelloWorld from '@/components/HelloWorld.vue'
import MyNewPage from '@/components/MyNewPage.vue'
const routes = [
{
path: '/', // 添加根路径路由
name: 'home', // 可以和 /helloworld 路由使用相同的名称,但通常根路径会使用 'Home' 或 'Index' 这样的名称
component: HelloWorld // 当访问 / 时,渲染 HelloWorld 组件
},
{
path: '/helloworld',
name: 'helloworld',
component: HelloWorld
},
{
path: '/mynewpage',
name: 'mynewpage',
component: MyNewPage
},
// 更多路由...
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes, // 简写为 `routes` 而不是 `routes: routes`
})
export default router
src/App.vue:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<router-link to="/">首页</router-link> |
<router-link to="/helloworld">helloworld</router-link> |
<router-link to="/mynewpage">mynewpage</router-link>
<!-- 我是分割线 -->
<div style="padding:30px 0;">-- 我是分割线 --</div>
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<!-- 路由匹配的组件将渲染在这里 必选项-->
<router-view/>
</template>
<script>
// import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
// components: {
// HelloWorld
// }
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Src/main.js:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 导入你的路由配置
// 创建 Vue 应用实例
const app = createApp(App)
// 使用路由插件
app.use(router)
// 挂载应用到 DOM 元素上
app.mount('#app')
配置完成后,再新建终端,
最终效果展示
App running at:
- Local: http://localhost:8081/
- Network: http://192.168.31.63:8081/