为了账号安全,请及时绑定邮箱和手机立即绑定

Vue3项目实战:从入门到上手

概述

本文将详细介绍如何从零开始搭建Vue3项目,涵盖环境搭建、组件开发、路由配置和状态管理等各个方面,帮助你快速上手Vue3项目实战。此外,还将通过构建一个简单的个人博客项目,进一步巩固所学知识。通过本文的学习,你将能够掌握Vue3的核心特性和最佳实践。

Vue3项目实战:从入门到上手
Vue3基础入门

介绍Vue3的主要特性和优势

Vue3是Vue.js的最新版本,它在性能、API设计、工具支持等多个方面进行了改进。以下是Vue3的主要特性和优势:

  1. TypeScript支持增强Vue3对TypeScript的支持进行了优化,包括改进的类型推断和更好的TypeScript错误提示。
  2. Composition API:引入了Composition API,它允许开发者更灵活地组织代码逻辑,更好地复用逻辑代码。
  3. 性能提升Vue3在渲染性能、内存占用和编译速度方面都有显著提升。
  4. Tree-shaking友好Vue3组件库的体积更小,更容易进行Tree-shaking,这意味着未使用的代码不会被包含在最终的构建包中。
  5. 更好的错误信息Vue3提供更清晰、更详细的错误信息,帮助开发者更快地定位问题。
  6. 更小的体积Vue3的核心库体积更小,接近于Vue2的1/2大小。

安装Vue3和设置开发环境

为了开始使用Vue3,你需要安装Node.js和npm。以下是安装步骤:

  1. 安装Node.js和npm

    • 访问Node.js官网下载并安装最新版本的Node.js。
    • 安装完成后,通过命令行验证安装成功:
      node -v
      npm -v
  2. 安装Vue CLI

    • Vue CLI是Vue.js项目的脚手架工具,你可以通过npm安装它:
      npm install -g @vue/cli
    • 验证Vue CLI是否安装成功:
      vue -V
  3. 安装Vue Devtools
    • Vue Devtools是一个浏览器扩展,用于调试Vue应用。可以在Chrome或Firefox等浏览器的扩展商店中搜索并安装。

创建第一个Vue3项目

使用Vue CLI创建一个新项目:

  1. 创建项目

    • 在命令行中运行以下命令:
      vue create my-vue3-app
    • 在提示中选择Vue 3预设:
      Manually select features
    • 选择“Vue 3 Preview”选项,然后选择你需要的其他特性,如Babel、Router、Vuex等。
  2. 运行项目
    • 进入项目目录:
      cd my-vue3-app
    • 安装依赖:
      npm install
    • 启动开发服务器:
      npm run serve
    • 打开浏览器,访问http://localhost:8080,查看项目的运行情况。

示例代码

// main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
<!-- App.vue -->
<template>
  <div id="app">
    <h1>Hello, Vue3!</h1>
  </div>
</template>
Vue3项目结构与配置

项目的基本文件结构

一个典型的Vue项目文件结构如下:

my-vue3-app/
├── public/
│   ├── index.html
│   └── favicon.ico
├── src/
│   ├── assets/
│   ├── components/
│   ├── App.vue
│   ├── main.js
│   └── router/
├── .gitignore
├── babel.config.js
├── package.json
└── vue.config.js
  • public/:存放静态资源文件。
  • src/:存放Vue应用的源代码。
  • assets/:存放静态文件,如图片。
  • components/:存放Vue组件。
  • App.vue:应用的主组件。
  • main.js:应用的主入口文件。
  • router/:存放路由配置。
  • .gitignore:配置Git忽略的文件。
  • babel.config.js:配置Babel。
  • package.json:项目配置文件。
  • vue.config.js:Vue CLI配置文件。

配置Babel和Webpack

Babel用于将ES6+代码转换为兼容ES5的代码,Webpack用于打包模块。

  1. 配置Babel

    • 在项目根目录中创建或编辑babel.config.js文件,添加以下内容:
      module.exports = {
      presets: [
       '@vue/cli-plugin-babel/preset'
      ]
      }
  2. 配置Webpack
    • vue.config.js文件中配置Webpack,例如:
      module.exports = {
      configureWebpack: {
       module: {
         rules: [
           {
             test: /\.css$/,
             use: [
               'style-loader',
               'css-loader'
             ]
           }
         ]
       }
      }
      }

使用Vue CLI快速搭建项目

Vue CLI提供了快速搭建Vue项目的命令:

  1. 创建项目

    • 使用vue create命令创建项目。
    • 在提示中选择Vue 3预设和所需特性。
  2. 生成组件
    • 使用vue generate component命令生成组件。
    • 示例:
      vue generate component Button

示例代码

// .vue.config.js
module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        }
      ]
    }
  }
}
Vue3组件开发

组件的定义和使用

在Vue中,组件是可复用的UI组件。一个Vue组件通常包含以下部分:

  • template:HTML模板。
  • script:组件的逻辑代码。
  • style:组件的样式。

例如,定义一个简单的组件:

<!-- Button.vue -->
<template>
  <button @click="handleClick">{{ message }}</button>
</template>

<script>
export default {
  data() {
    return {
      message: 'Click me'
    }
  },
  methods: {
    handleClick() {
      alert('Button clicked!')
    }
  }
}
</script>

<style scoped>
button {
  padding: 10px 20px;
  border: none;
  background-color: #42b883;
  color: white;
  cursor: pointer;
}
</style>

Props和事件的传递

Props允许父组件向子组件传递数据,事件则允许子组件触发父组件的方法。

  1. 定义Props

    • 在子组件中定义Props:
      export default {
      props: {
       message: String
      }
      }
  2. 传递Props

    • 在父组件中使用子组件并传递Props:
      <template>
      <Button message="Hello, Props!" />
      </template>
  3. 触发事件
    • 在子组件中触发事件:
      <button @click="$emit('click')"></button>
    • 在父组件中监听事件:
      <Button @click="handleClick"></Button>

插槽(Slots)的概念与应用

插槽允许将子组件的一部分内容替换为父组件的内容。

  1. 定义插槽

    • 在子组件中定义插槽:
      <template>
      <div>
       <slot></slot>
      </div>
      </template>
  2. 使用插槽
    • 在父组件中使用插槽:
      <ChildComponent>
      <span>Custom content here</span>
      </ChildComponent>

示例代码

<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <span>Custom content here</span>
  </ChildComponent>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  }
}
</script>
<!-- ChildComponent.vue -->
<template>
  <div>
    <slot></slot>
  </div>
</template>
Vue3响应式原理与实践

响应式系统的工作机制

Vue3的响应式系统基于Proxy对象。当数据发生变化时,Vue会自动触发视图更新。

  1. Proxy对象

    • Vue3使用Proxy对象来监听数据的变化。
    • 当访问或修改数据时,Proxy对象会拦截这些操作,从而触发相应的回调函数。
  2. ref和reactive的区别
    • ref用于包装基本类型的数据,使其具有响应式特性。
    • reactive用于包装复杂类型的数据(如对象和数组),使其具有响应式特性。

ref和reactive的区别与使用场景

  1. ref

    • ref用于包装基本类型的数据。
    • 示例:

      import { ref } from 'vue'
      
      const count = ref(0)
      
      // 访问ref包装的数据
      console.log(count.value) // 0
      
      // 修改ref包装的数据
      count.value++
  2. reactive

    • reactive用于包装复杂类型的数据。
    • 示例:

      import { reactive } from 'vue'
      
      const state = reactive({
      count: 0,
      message: 'Hello, Vue3!'
      })
      
      // 访问reactive包装的数据
      console.log(state.count) // 0
      console.log(state.message) // 'Hello, Vue3!'
      
      // 修改reactive包装的数据
      state.count++
      state.message = 'New message'

响应式数据的监听与修改

  1. 监听数据变化

    • 使用watch来监听数据的变化。
    • 示例:

      import { reactive, watch } from 'vue'
      
      const state = reactive({
      count: 0
      })
      
      watch(
      () => state.count,
      (newVal, oldVal) => {
       console.log(`count changed from ${oldVal} to ${newVal}`)
      }
      )
      
      state.count++ // 触发watch回调
  2. 修改响应式数据

    • 直接修改响应式数据即可触发视图更新。
    • 示例:

      import { reactive } from 'vue'
      
      const state = reactive({
      count: 0
      })
      
      state.count++ // 触发视图更新

示例代码

// main.js
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

const count = ref(0)
const state = reactive({
  count: 0,
  message: 'Hello, Vue3!'
})

watch(
  () => state.count,
  (newVal, oldVal) => {
    console.log(`count changed from ${oldVal} to ${newVal}`)
  }
)

app.mount('#app')
<!-- App.vue -->
<template>
  <div>
    <h1>{{ count }}</h1>
    <h2>{{ state.count }}, {{ state.message }}</h2>
  </div>
</template>

<script>
import { ref, reactive, watch } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const state = reactive({
      count: 0,
      message: 'Hello, Vue3!'
    })

    watch(
      () => state.count,
      (newVal, oldVal) => {
        console.log(`count changed from ${oldVal} to ${newVal}`)
      }
    )

    return {
      count,
      state
    }
  }
}
</script>
Vue3路由与状态管理

Vue Router的基本使用

Vue Router是Vue应用的官方路由库。它可以实现页面的动态路由和导航。

  1. 安装Vue Router

    • 使用npm安装Vue Router:
      npm install vue-router@next
  2. 配置路由

    • 在项目中创建一个router目录,并在其中创建index.js文件:

      import { createRouter, createWebHistory } from 'vue-router'
      import Home from '../views/Home.vue'
      import About from '../views/About.vue'
      
      const routes = [
      {
       path: '/',
       name: 'Home',
       component: Home
      },
      {
       path: '/about',
       name: 'About',
       component: About
      }
      ]
      
      const router = createRouter({
      history: createWebHistory(),
      routes
      })
      
      export default router
  3. 在主应用中使用路由

    • main.js中引入并使用路由:

      import { createApp } from 'vue'
      import App from './App.vue'
      import router from './router'
      
      createApp(App).use(router).mount('#app')
  4. 使用导航链接
    • 在组件中使用<router-link>标签进行导航:
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>

Router的高级配置

  1. 动态路由

    • 动态路由可以匹配任何路径:
      {
      path: '/user/:id',
      name: 'User',
      component: () => import('../views/User.vue')
      }
  2. 命名视图

    • 使用命名视图可以渲染多个视图:
      <router-view name="main"></router-view>
      <router-view name="sidebar"></router-view>
  3. 编程式导航
    • 使用router.pushrouter.replace进行编程式导航:
      this.$router.push('/about')
      this.$router.replace('/about')

Vuex的安装和基本使用

Vuex是Vue的官方状态管理库。它提供了状态集中管理和异步操作的解决方案。

  1. 安装Vuex

    • 使用npm安装Vuex:
      npm install vuex@next
  2. 配置Vuex

    • 创建一个store目录,并在其中创建index.js文件:

      import { createStore } from 'vuex'
      
      const store = createStore({
      state: {
       count: 0
      },
      mutations: {
       increment(state) {
         state.count++
       }
      },
      actions: {
       increment({ commit }) {
         commit('increment')
       }
      },
      getters: {
       count(state) {
         return state.count
       }
      }
      })
      
      export default store
  3. 在主应用中使用Vuex

    • main.js中引入并使用Vuex:

      import { createApp } from 'vue'
      import App from './App.vue'
      import store from './store'
      
      createApp(App).use(store).mount('#app')
  4. 在组件中使用Vuex

    • 在组件中通过computed属性或mapState辅助函数访问状态:

      import { computed, useStore } from 'vue'
      
      export default {
      setup() {
       const store = useStore()
       const count = computed(() => store.state.count)
      
       return {
         count
       }
      }
      }

示例代码

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
// store/index.js
import { createStore } from 'vuex'

const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    increment({ commit }) {
      commit('increment')
    }
  },
  getters: {
    count(state) {
      return state.count
    }
  }
})

export default store
<!-- App.vue -->
<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
import { computed, useStore } from 'vue'

export default {
  setup() {
    const store = useStore()
    const count = computed(() => store.state.count)

    return {
      count
    }
  }
}
</script>
Vue3项目实战:构建个人博客

项目需求分析

构建一个简单的个人博客系统,包含以下功能:

  1. 用户管理
    • 登录/注册。
    • 用户个人资料。
  2. 文章管理
    • 发布文章。
    • 编辑文章。
    • 删除文章。
  3. 文章分类
    • 文章分类展示。
    • 文章分类管理。
  4. 文章评论
    • 发表评论。
    • 回复评论。

设计项目结构

项目的基本结构如下:

my-vue3-app/
├── public/
├── src/
│   ├── assets/
│   ├── components/
│   ├── views/
│   ├── router/
│   ├── store/
│   ├── App.vue
│   ├── main.js
│   ├── index.html
│   └── router.js
├── .gitignore
├── babel.config.js
├── package.json
└── vue.config.js

实现页面功能

  1. 登录/注册页面

    • 创建Login.vueRegister.vue组件。
    • 使用表单提交数据到后端API。
    • 示例:

      <!-- Login.vue -->
      <template>
      <form @submit.prevent="handleSubmit">
       <input type="email" v-model="email" placeholder="Email" />
       <input type="password" v-model="password" placeholder="Password" />
       <button>Login</button>
      </form>
      </template>
      
      <script>
      export default {
      data() {
       return {
         email: '',
         password: ''
       }
      },
      methods: {
       handleSubmit() {
         // 提交表单数据到后端API
         console.log(this.email, this.password)
       }
      }
      }
      </script>
  2. 用户个人资料页面

    • 创建Profile.vue组件。
    • 显示用户的信息。
    • 提供编辑用户信息的功能。
    • 示例:

      <!-- Profile.vue -->
      <template>
      <div>
       <h1>User Profile</h1>
       <form @submit.prevent="handleSubmit">
         <input type="text" v-model="name" placeholder="Name" />
         <input type="email" v-model="email" placeholder="Email" />
         <button>Edit</button>
       </form>
      </div>
      </template>
      
      <script>
      export default {
      data() {
       return {
         name: 'John Doe',
         email: 'john@example.com'
       }
      },
      methods: {
       handleSubmit() {
         // 提交表单数据到后端API
         console.log(this.name, this.email)
       }
      }
      }
      </script>
  3. 文章管理页面

    • 创建ArticleList.vueArticleEdit.vue组件。
    • ArticleList显示文章列表。
    • ArticleEdit用于编辑文章。
    • 示例:

      <!-- ArticleList.vue -->
      <template>
      <ul>
       <li v-for="article in articles" :key="article.id">
         {{ article.title }}
       </li>
      </ul>
      </template>
      
      <script>
      export default {
      data() {
       return {
         articles: [
           { id: 1, title: 'Title 1' },
           { id: 2, title: 'Title 2' }
         ]
       }
      }
      }
      </script>
      <!-- ArticleEdit.vue -->
      <template>
      <form @submit.prevent="handleSubmit">
       <input type="text" v-model="title" placeholder="Title" />
       <button>Save</button>
      </form>
      </template>
      
      <script>
      export default {
      data() {
       return {
         title: ''
       }
      },
      methods: {
       handleSubmit() {
         // 提交表单数据到后端API
         console.log(this.title)
       }
      }
      }
      </script>
  4. 文章分类页面

    • 创建CategoryList.vueCategoryEdit.vue组件。
    • CategoryList显示文章分类列表。
    • CategoryEdit用于编辑文章分类。
    • 示例:

      <!-- CategoryList.vue -->
      <template>
      <ul>
       <li v-for="category in categories" :key="category.id">
         {{ category.name }}
       </li>
      </ul>
      </template>
      
      <script>
      export default {
      data() {
       return {
         categories: [
           { id: 1, name: 'Category 1' },
           { id: 2, name: 'Category 2' }
         ]
       }
      }
      }
      </script>
      <!-- CategoryEdit.vue -->
      <template>
      <form @submit.prevent="handleSubmit">
       <input type="text" v-model="name" placeholder="Name" />
       <button>Save</button>
      </form>
      </template>
      
      <script>
      export default {
      data() {
       return {
         name: ''
       }
      },
      methods: {
       handleSubmit() {
         // 提交表单数据到后端API
         console.log(this.name)
       }
      }
      }
      </script>
  5. 文章评论页面

    • 创建CommentList.vueCommentEdit.vue组件。
    • CommentList显示文章评论列表。
    • CommentEdit用于发表评论。
    • 示例:

      <!-- CommentList.vue -->
      <template>
      <ul>
       <li v-for="comment in comments" :key="comment.id">
         {{ comment.text }}
       </li>
      </ul>
      </template>
      
      <script>
      export default {
      data() {
       return {
         comments: [
           { id: 1, text: 'Comment 1' },
           { id: 2, text: 'Comment 2' }
         ]
       }
      }
      }
      </script>
      <!-- CommentEdit.vue -->
      <template>
      <form @submit.prevent="handleSubmit">
       <input type="text" v-model="text" placeholder="Comment" />
       <button>Submit</button>
      </form>
      </template>
      
      <script>
      export default {
      data() {
       return {
         text: ''
       }
      },
      methods: {
       handleSubmit() {
         // 提交表单数据到后端API
         console.log(this.text)
       }
      }
      }
      </script>

项目部署与上线

  1. 构建项目

    • 使用npm run build命令构建项目。
    • 构建后的文件位于dist目录下。
  2. 部署到服务器

    • dist目录下的文件上传到服务器。
    • 配置服务器的静态文件服务,例如使用Nginx或Apache。
  3. 域名绑定

    • 在域名提供商处绑定域名到服务器IP地址。
  4. SSL证书
    • 购买或申请SSL证书,并配置服务器以支持HTTPS。

示例代码

# 构建项目
npm run build

# 部署到服务器
scp -r dist/* user@your.server.com:/var/www/yourdomain.com
总结

通过以上步骤,你已经掌握了Vue3项目的入门到上手的全过程。从环境搭建、组件开发、路由与状态管理,再到实战项目构建,你能够使用Vue3开发出功能完善、结构清晰的Web应用。希望这篇文章能帮助你更好地理解Vue3,提高你的开发技能。如果你需要进一步学习或解决遇到的问题,推荐访问Muimooc

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消