vue.js项目实战案例源码

案例一:博客系统

项目概述:
一个简单的博客系统,包括文章列表展示、文章详情查看、分类筛选、用户登录注册等功能。

技术栈:

  • Vue.js
  • Vue Router
  • Vuex
  • Axios
  • Bootstrap

主要功能实现:

  1. 文章列表展示
    • 使用 Axios 从后端 API 获取文章列表数据。
    • 在 Vue 组件中展示文章标题、摘要和发布日期等信息。
   <template>
     <div>
       <h1>博客文章列表</h1>
       <ul>
         <li v-for="article in articles" :key="article.id">
           <a :href="'/article/' + article.id">{{ article.title }}</a>
           <p>{{ article.summary }}</p>
           <small>{{ article.publishedDate }}</small>
         </li>
       </ul>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         articles: []
       };
     },
     async created() {
       try {
         const response = await axios.get('/api/articles');
         this.articles = response.data;
       } catch (error) {
         console.error('获取文章列表失败:', error);
       }
     }
   };
   </script>

  1. 文章详情查看
    • 通过 Vue Router 的动态路由参数获取文章 ID。
    • 从后端获取特定文章的详细内容并展示。
   <template>
     <div>
       <h1>{{ article.title }}</h1>
       <p>{{ article.content }}</p>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         article: {}
       };
     },
     async created() {
       const articleId = this.$route.params.id;
       try {
         const response = await axios.get(`/api/articles/${articleId}`);
         this.article = response.data;
       } catch (error) {
         console.error('获取文章详情失败:', error);
       }
     }
   };
   </script>

  1. 分类筛选
    • 展示不同的文章分类,用户点击分类可筛选出相应的文章列表。
   <template>
     <div>
       <h1>博客文章列表</h1>
       <ul>
         <li v-for="category in categories" :key="category.id">
           <a @click.prevent="filterArticlesByCategory(category.id)">{{ category.name }}</a>
         </li>
       </ul>
       <ul>
         <li v-for="article in filteredArticles" :key="article.id">
           <a :href="'/article/' + article.id">{{ article.title }}</a>
           <p>{{ article.summary }}</p>
           <small>{{ article.publishedDate }}</small>
         </li>
       </ul>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         articles: [],
         categories: [],
         filteredArticles: []
       };
     },
     async created() {
       try {
         const articlesResponse = await axios.get('/api/articles');
         this.articles = articlesResponse.data;

         const categoriesResponse = await axios.get('/api/categories');
         this.categories = categoriesResponse.data;
       } catch (error) {
         console.error('获取数据失败:', error);
       }
     },
     methods: {
       filterArticlesByCategory(categoryId) {
         this.filteredArticles = this.articles.filter(article => article.categoryId === categoryId);
       }
     }
   };
   </script>

  1. 用户登录注册
    • 提供登录和注册表单,用户输入用户名、密码等信息进行操作。
    • 使用 Axios 与后端进行交互,验证用户信息并处理登录注册流程。
   <template>
     <div>
       <h2>登录</h2>
       <form @submit.prevent="login">
         <input type="text" v-model="username" placeholder="用户名">
         <input type="password" v-model="password" placeholder="密码">
         <button type="submit">登录</button>
       </form>
       <h2>注册</h2>
       <form @submit.prevent="register">
         <input type="text" v-model="newUsername" placeholder="用户名">
         <input type="password" v-model="newPassword" placeholder="密码">
         <button type="submit">注册</button>
       </form>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         username: '',
         password: '',
         newUsername: '',
         newPassword: ''
       };
     },
     methods: {
       async login() {
         try {
           const response = await axios.post('/api/login', {
             username: this.username,
             password: this.password
           });
           // 处理登录成功后的操作
           console.log('登录成功', response.data);
         } catch (error) {
           console.error('登录失败:', error);
         }
       },
       async register() {
         try {
           const response = await axios.post('/api/register', {
             username: this.newUsername,
             password: this.newPassword
           });
           // 处理注册成功后的操作
           console.log('注册成功', response.data);
         } catch (error) {
           console.error('注册失败:', error);
         }
       }
     }
   };
   </script>

案例二:电商购物网站

项目概述:
一个具有商品展示、购物车、订单管理等功能的电商购物网站。

技术栈:

  • Vue.js
  • Vue Router
  • Vuex
  • Axios
  • Element UI

主要功能实现:

  1. 商品展示
    • 从后端获取商品列表数据,包括商品图片、名称、价格、描述等信息。
    • 使用 Vue 的列表渲染指令展示商品列表。
   <template>
     <div>
       <h1>商品列表</h1>
       <ul>
         <li v-for="product in products" :key="product.id">
           <img :src="product.image" alt="Product Image">
           <h2>{{ product.name }}</h2>
           <p>{{ product.price }}</p>
           <button @click="addToCart(product)">加入购物车</button>
         </li>
       </ul>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         products: []
       };
     },
     async created() {
       try {
         const response = await axios.get('/api/products');
         this.products = response.data;
       } catch (error) {
         console.error('获取商品列表失败:', error);
       }
     },
     methods: {
       addToCart(product) {
         // 将商品添加到购物车的逻辑
         console.log('添加商品到购物车:', product);
       }
     }
   };
   </script>

  1. 购物车功能
    • 维护一个购物车状态,包括已添加的商品和数量。
    • 提供购物车页面展示购物车中的商品列表,以及总价计算等功能。
   <template>
     <div>
       <h1>购物车</h1>
       <ul>
         <li v-for="item in cartItems" :key="item.product.id">
           <img :src="item.product.image" alt="Product Image">
           <h2>{{ item.product.name }}</h2>
           <p>{{ item.product.price }}</p>
           <input type="number" v-model="item.quantity">
           <button @click="removeFromCart(item.product.id)">移除</button>
         </li>
       </ul>
       <p>总价:{{ totalPrice }}</p>
       <button @click="checkout">结算</button>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {
         cartItems: [],
         totalPrice: 0
       };
     },
     computed: {
       totalPrice() {
         return this.cartItems.reduce((total, item) => total + item.product.price * item.quantity, 0);
       }
     },
     methods: {
       addToCart(product) {
         const existingItem = this.cartItems.find(item => item.product.id === product.id);
         if (existingItem) {
           existingItem.quantity++;
         } else {
           this.cartItems.push({ product, quantity: 1 });
         }
       },
       removeFromCart(productId) {
         this.cartItems = this.cartItems.filter(item => item.product.id!== productId);
       },
       checkout() {
         // 结算逻辑
         console.log('结算购物车');
       }
     }
   };
   </script>

  1. 订单管理
    • 用户提交订单后,将订单信息发送到后端进行处理。
    • 提供订单列表页面,展示用户的历史订单。
   <template>
     <div>
       <h1>订单列表</h1>
       <ul>
         <li v-for="order in orders" :key="order.id">
           <p>订单编号:{{ order.id }}</p>
           <p>订单日期:{{ order.orderDate }}</p>
           <ul>
             <li v-for="item in order.items" :key="item.product.id">
               <img :src="item.product.image" alt="Product Image">
               <h2>{{ item.product.name }}</h2>
               <p>{{ item.product.price }}</p>
               <p>数量:{{ item.quantity }}</p>
             </li>
           </ul>
           <p>总价:{{ order.totalPrice }}</p>
         </li>
       </ul>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         orders: []
       };
     },
     async created() {
       try {
         const response = await axios.get('/api/orders');
         this.orders = response.data;
       } catch (error) {
         console.error('获取订单列表失败:', error);
       }
     }
   };
   </script>

案例三:任务管理应用

项目概述:
一个用于管理个人或团队任务的应用,包括任务创建、编辑、标记完成、分类等功能。

技术栈:

  • Vue.js
  • Vue Router
  • Vuex
  • Bootstrap Vue

主要功能实现:

  1. 任务列表展示
    • 从后端获取任务列表数据,展示任务的标题、描述、截止日期等信息。
   <template>
     <div>
       <h1>任务列表</h1>
       <ul>
         <li v-for="task in tasks" :key="task.id">
           <input type="checkbox" v-model="task.completed">
           <span v-if="task.completed" class="completed">{{ task.title }}</span>
           <span v-else>{{ task.title }}</span>
           <p>{{ task.description }}</p>
           <small>{{ task.dueDate }}</small>
           <button @click="editTask(task.id)">编辑</button>
           <button @click="deleteTask(task.id)">删除</button>
         </li>
       </ul>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         tasks: []
       };
     },
     async created() {
       try {
         const response = await axios.get('/api/tasks');
         this.tasks = response.data;
       } catch (error) {
         console.error('获取任务列表失败:', error);
       }
     },
     methods: {
       async editTask(taskId) {
         // 编辑任务的逻辑
         console.log('编辑任务:', taskId);
       },
       async deleteTask(taskId) {
         try {
           await axios.delete(`/api/tasks/${taskId}`);
           this.tasks = this.tasks.filter(task => task.id!== taskId);
         } catch (error) {
           console.error('删除任务失败:', error);
         }
       }
     }
   };
   </script>

  1. 任务创建和编辑
    • 提供任务创建表单,用户输入任务标题、描述、截止日期等信息创建新任务。
    • 编辑现有任务时,预填充任务信息并允许用户修改。
   <template>
     <div>
       <h2 v-if="editingTask">编辑任务</h2>
       <h2 v-else>创建任务</h2>
       <form @submit.prevent="submitTask">
         <input type="text" v-model="task.title" placeholder="任务标题">
         <textarea v-model="task.description" placeholder="任务描述"></textarea>
         <input type="date" v-model="task.dueDate">
         <button type="submit">{{ editingTask? '保存' : '创建' }}</button>
       </form>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {
         task: {
           title: '',
           description: '',
           dueDate: ''
         },
         editingTask: false
       };
     },
     methods: {
       async submitTask() {
         if (this.editingTask) {
           try {
             await axios.put(`/api/tasks/${this.task.id}`, this.task);
             // 更新任务列表
             console.log('任务编辑成功');
           } catch (error) {
             console.error('任务编辑失败:', error);
           }
         } else {
           try {
             const response = await axios.post('/api/tasks', this.task);
             // 将新任务添加到任务列表
             console.log('任务创建成功');
           } catch (error) {
             console.error('任务创建失败:', error);
           }
         }
         this.task = {
           title: '',
           description: '',
           dueDate: ''
         };
         this.editingTask = false;
       }
     }
   };
   </script>

  1. 任务分类
    • 允许用户为任务添加标签或分类,以便更好地组织任务。

案例四:音乐播放器

项目概述:
一个简单的音乐播放器,支持播放、暂停、上一曲、下一曲、音量调节等功能。

技术栈:

  • Vue.js
  • Vue Router
  • Axios
  • Howler.js

主要功能实现:

  1. 音乐播放
    • 使用 Howler.js 库加载和播放音乐文件。
    • 在 Vue 组件中设置播放按钮,点击时触发播放或暂停操作。
   <template>
     <div>
       <h1>音乐播放器</h1>
       <audio ref="audioPlayer" controls>
         <source :src="currentSong.url" type="audio/mpeg">
       </audio>
       <button @click="togglePlay">播放/暂停</button>
     </div>
   </template>

   <script>
   import Howl from 'howler';

   export default {
     data() {
       return {
         currentSong: {
           url: '',
           title: ''
         },
         isPlaying: false
       };
     },
     mounted() {
       // 假设从后端获取音乐列表后设置当前歌曲
       this.currentSong = {
         url: 'path/to/song.mp3',
         title: 'Song Title'
       };
     },
     methods: {
       togglePlay() {
         if (this.isPlaying) {
           this.$refs.audioPlayer.pause();
         } else {
           this.$refs.audioPlayer.play();
         }
         this.isPlaying =!this.isPlaying;
       }
     }
   };
   </script>

  1. 上一曲 / 下一曲
    • 维护一个音乐列表,当用户点击上一曲或下一曲按钮时,切换当前播放的歌曲。
   <template>
     <div>
       <h1>音乐播放器</h1>
       <audio ref="audioPlayer" controls>
         <source :src="currentSong.url" type="audio/mpeg">
       </audio>
       <button @click="previousSong">上一曲</button>
       <button @click="togglePlay">播放/暂停</button>
       <button @click="nextSong">下一曲</button>
     </div>
   </template>

   <script>
   import Howl from 'howler';

   export default {
     data() {
       return {
         songs: [
           { url: 'path/to/song1.mp3', title: 'Song 1' },
           { url: 'path/to/song2.mp3', title: 'Song 2' },
           { url: 'path/to/song3.mp3', title: 'Song 3' }
         ],
         currentSongIndex: 0,
         currentSong: {
           url: '',
           title: ''
         },
         isPlaying: false
       };
     },
     mounted() {
       this.currentSong = this.songs[this.currentSongIndex];
     },
     methods: {
       togglePlay() {
         if (this.isPlaying) {
           this.$refs.audioPlayer.pause();
         } else {
           this.$refs.audioPlayer.play();
         }
         this.isPlaying =!this.isPlaying;
       },
       previousSong() {
         if (this.currentSongIndex > 0) {
           this.currentSongIndex--;
         } else {
           this.currentSongIndex = this.songs.length - 1;
         }
         this.currentSong = this.songs[this.currentSongIndex];
         this.$refs.audioPlayer.load();
         this.$refs.audioPlayer.play();
         this.isPlaying = true;
       },
       nextSong() {
         if (this.currentSongIndex < this.songs.length - 1) {
           this.currentSongIndex++;
         } else {
           this.currentSongIndex = 0;
         }
         this.currentSong = this.songs[this.currentSongIndex];
         this.$refs.audioPlayer.load();
         this.$refs.audioPlayer.play();
         this.isPlaying = true;
       }
     }
   };
   </script>

  1. 音量调节
    • 通过输入框或滑块来调整音乐的音量大小。
   <template>
     <div>
       <h1>音乐播放器</h1>
       <audio ref="audioPlayer" controls>
         <source :src="currentSong.url" type="audio/mpeg">
       </audio>
       <button @click="previousSong">上一曲</button>
       <button @click="togglePlay">播放/暂停</button>
       <button @click="nextSong">下一曲</button>
       <input type="range" min="0" max="1" step="0.1" v-model="volume" @input="setVolume">
     </div>
   </template>

   <script>
   import Howl from 'howler';

   export default {
     data() {
       return {
         songs: [
           { url: 'path/to/song1.mp3', title: 'Song 1' },
           { url: 'path/to/song2.mp3', title: 'Song 2' },
           { url: 'path/to/song3.mp3', title: 'Song 3' }
         ],
         currentSongIndex: 0,
         currentSong: {
           url: '',
           title: ''
         },
         isPlaying: false,
         volume: 1
       };
     },
     mounted() {
       this.currentSong = this.songs[this.currentSongIndex];
     },
     methods: {
       togglePlay() {
         if (this.isPlaying) {
           this.$refs.audioPlayer.pause();
         } else {
           this.$refs.audioPlayer.play();
         }
         this.isPlaying =!this.isPlaying;
       },
       previousSong() {
         if (this.currentSongIndex > 0) {
           this.currentSongIndex--;
         } else {
           this.currentSongIndex = this.songs.length - 1;
         }
         this.currentSong = this.songs[this.currentSongIndex];
         this.$refs.audioPlayer.load();
         this.$refs.audioPlayer.play();
         this.isPlaying = true;
       },
       nextSong() {
         if (this.currentSongIndex < this.songs.length - 1) {
           this.currentSongIndex++;
         } else {
           this.currentSongIndex = 0;
         }
         this.currentSong = this.songs[this.currentSongIndex];
         this.$refs.audioPlayer.load();
         this.$refs.audioPlayer.play();
         this.isPlaying = true;
       },
       setVolume() {
         this.$refs.audioPlayer.volume(this.volume);
       }
     }
   };
   </script>

案例五:天气应用

项目概述:
一个显示当前天气状况和未来天气预报的应用。

技术栈:

  • Vue.js
  • Vue Router
  • Axios
  • OpenWeatherMap API

主要功能实现:

  1. 获取天气数据
    • 使用 Axios 调用 OpenWeatherMap API 获取当前天气和未来天气预报数据。
   <template>
     <div>
       <h1>天气应用</h1>
       <p v-if="loading">正在加载天气数据...</p>
       <div v-else>
         <h2>{{ cityName }}</h2>
         <p>{{ currentWeather.temperature }}°C</p>
         <p>{{ currentWeather.description }}</p>
         <ul>
           <li v-for="forecast in forecastData" :key="forecast.date">
             <p>{{ forecast.date }}</p>
             <p>{{ forecast.temperature }}°C</p>
             <p>{{ forecast.description }}</p>
           </li>
         </ul>
       </div>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         cityName: '',
         currentWeather: {},
         forecastData: [],
         loading: true
       };
     },
     async created() {
       const apiKey = 'your_api_key';
       const city = 'your_city';
       try {
         const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
         this.cityName = response.data.name;
         this.currentWeather = {
           temperature: response.data.main.temp - 273.15,
           description: response.data.weather[0].description
         };
         const forecastResponse = await axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`);
         this.forecastData = forecastResponse.data.list.map(item => ({
           date: item.dt_txt,
           temperature: item.main.temp - 273.15,
           description: item.weather[0].description
         }));
         this.loading = false;
       } catch (error) {
         console.error('获取天气数据失败:', error);
         this.loading = false;
       }
     }
   };
   </script>

  1. 显示天气信息
    • 在页面上展示当前城市名称、温度、天气描述以及未来几天的天气预报。
   <template>
     <div>
       <h1>天气应用</h1>
       <p v-if="loading">正在加载天气数据...</p>
       <div v-else>
         <h2>{{ cityName }}</h2>
         <p>{{ currentWeather.temperature }}°C</p>
         <p>{{ currentWeather.description }}</p>
         <ul>
           <li v-for="forecast in forecastData" :key="forecast.date">
             <p>{{ forecast.date }}</p>
             <p>{{ forecast.temperature }}°C</p>
             <p>{{ forecast.description }}</p>
           </li>
         </ul>
       </div>
     </div>
   </template>

   <script>
   import axios from 'axios';

   export default {
     data() {
       return {
         cityName: '',
         currentWeather: {},
         forecastData: [],
         loading: true
       };
     },
     async created() {
       const apiKey = 'your_api_key';
       const city = 'your_city';
       try {
         const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`);
         this.cityName = response.data.name;
         this.currentWeather = {
           temperature: response.data.main.temp - 273.15,
           description: response.data.weather[0].description
         };
         const forecastResponse = await axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`);
         this.forecastData = forecastResponse.data.list.map(item => ({
           date: item.dt_txt,
           temperature: item.main.temp - 273.15,
           description: item.weather[0].description
         }));
         this.loading = false;
       } catch (error) {
         console.error('获取天气数据失败:', error);
         this.loading = false;
       }
     }
   };
   </script>

这些案例展示了 Vue.js 在不同项目中的应用,可以帮助你更好地理解 Vue.js 的实际开发过程和各种功能的实现方法。每个案例都可以根据具体需求进行进一步的扩展和优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值