總是從園子里索取,所以也想寫點東西,歡迎大家批評指教。
最近由於一些原因,開始學習vue的項目開發,對於我這樣一個剛剛入行的菜鳥級c#程序員,可真踩了不少坑,
接下來,廢話少說。
一、搭建環境
本人win10開發環境(資深大佬勿噴,我沒有mac,也沒有安裝linux環境)
1.首先安裝node環境,本項目中主要是用來做包管理。傳送門(https://nodejs.org/zh-cn/)
2.安裝vue
打開控制台輸入,並等待完成
npm insatll vue -g
3.安裝vue-cli(腳手架),用來構建項目。傳送門(https://segmentfault.com/a/1190000008644830)
npm install -g vue-cli
我們這里使用webpack作為腳手架,初始化我們的項目(注意,項目名必須是小寫)
vue init wepcak my-project
二、項目目錄
1.目錄如下(Visual Studio Code 個人認為挺好用的)

我們現在可以進入項目目錄(根據自己的項目名)
cd my-project
npm run dev // 這樣就可以看到我們剛剛構建的項目,相信你也和我一樣懵逼吧。
2.進行我們的改造,接下來才是正題(Code Show)
我們的源碼主要是在src目錄下,(刪除該目錄下原始文件)
目錄情況如下
|-------src
| |-- components
| | |-- Main.vue
| | |-- Login.vue
| |-- main.js
|------- index.html (提示,在根目錄下)
- index.html 代碼如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>my-project</title> </head> <body> <div id="app"> </div> <!-- built files will be auto injected --> </body> </html>
- /src/main.js 代碼如下
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' // 引入vue.js插件 import VueRouter from 'vue-router' // 組件 import Main from './components/Main.vue' import Login from './components/Login.vue' Vue.config.productionTip = false const routes = [ { name: 'main', path: '/', component: Main }, { name: 'login', path: '/login', component: Login } ] var router = new VueRouter({ routes }) Vue.use(VueRouter) var App = { template: '<router-view></router-view>' } /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
- /src/components/Login.vue
<template> <div class="login"> <div class="input-wrap"> <input type="text" v-model="name"/> <span v-if="error.name" class="err-msg">{{error.name}}</span> </div> <div class="input-wrap"> <input type="password" v-model="pwd"/> <span v-if="error.pwd" class="err-msg">{{error.pwd}}</span> </div> <div class="input-wrap"> <button @click="login">提交</button> </div> </div> </template> <script> export default { data() { return { name: '', pwd : '', error : { name: '', pwd : '' } } }, methods : { check(name,pwd) { if(!name) { this.error.name = '請輸入姓名' return false } if(!pwd){ this.error.pwd = '請輸入密碼' return false } }, login() { const { name, pwd, $router} = this if(!this.check(name,pwd)) return if(name == 'admin' && pwd == '123'){ $.router.push({ name : 'main' }) } else { alert('用戶名錯誤') } } } } </script> <style scoped lang="scss"> .login { width: 300px; margin: 10% auto; } </style> - /src/components/Main.vue
<template> <div class="main"> <h1>{{ msg }}</h1> </div> </template> <script> export default { data () { return { msg: 'Welcome to the Vue.js' } } } </script> <style> .main { font-size: 14px; color: #58666e; background-color: #1c2b36 } </style>項目完成。 在命令台輸入以下代碼
npm run dev
在瀏覽器輸入 http://localhost:8080,即可進入登陸頁面。 用戶名:amin 密碼 :123
三、效果圖


四、總結
本次示例采用的是vue2.0版本,希望大家批評指正不當之處。
源碼奉上 2018-03-2416:03:57
