咱们将会选择使用一些 vue 周边的库vue-cli
, vue-router
,vue-resource
,vuex
css
1.使用 vue-cli 建立项目
2.使用 vue-router 实现单页路由
3.使用 vuex 管理咱们的数据流
4.使用 vue-resource 请求咱们的 node 服务端
5.使用 .vue文 件进行组件化的开发
PS:本文 node v6.2.2 npm v3.9.5 vue v2.1.0 vue-router v2.0.3 vuex v2.0.0html
最终咱们将会构建出一个小 demo,不废话,直接上图。vue
1.咱们将会使用 webpack 去为咱们的模块打包,预处理,热加载。若是你对 webpack 不熟悉,它就是能够帮助咱们把多个 js 文件打包为1个入口文件,而且能够达到按需加载。这就意味着,咱们不用担忧因为使用太多的组件,致使了过多的 HTTP 请求,这是很是有益于产品体验的。但咱们并不仅是为了这个而使用 webpack,咱们须要用 webpack 去编译 .vue 文件,若是没有使用一个 loader 去转换咱们 .vue 文件里的 style、js 和 html,那么浏览器就没法识别。node
2.模块热加载是 webpack 的一个很是碉堡的特性,将会为咱们的单页应用带来极大的便利。
一般来讲,当咱们修改了代码刷新页面,那应用里的全部状态就都没有了。这对于开发一个单页应用来讲是很是痛苦的,由于须要从新在跑一遍流程。若是有模块热加载,当你修改了代码,你的代码会直接修改,页面并不会刷新,因此状态也会被保留。webpack
3.Vue 也为咱们提供了 CSS 预处理,因此咱们能够选择在 .vue 文件里写 LESS 或者 SASS 去代替原生 CSS。git
4.咱们过去一般须要使用 npm 下载一堆的依赖,可是如今咱们能够选择 Vue-cli。这是一个 vue 生态系统中一个伟大创举。这意味着咱们不须要手动构建咱们的项目,而它就能够很快地为咱们生成。github
首先,安装 vue-cli。(确保你有 node 和 npm)web
npm i -g vue-cli
vue-router
而后建立一个 webpack 项目而且下载依赖vuex
vue init webpack vue-tutorial
cd vue-tutorial
npm i
接着使用 npm run dev
在热加载中运行咱们的应用
这一行命令表明着它会去找到package.json
的scripts
对象,执行node bulid/dev-server.js
。在这文件里,配置了 Webpack,会让它去编译项目文件,而且运行服务器,咱们在localhost:8080
便可查看咱们的应用。
这些都准备好后,咱们须要为咱们的路由、XHR 请求、数据管理下载三个库,咱们能够从 vue 的官网中找到他们。另外咱们使用bootstrap
做为个人 UI 库
npm i vue-resource vue-router vuex bootstrap --save
查看咱们的应用文件,咱们能够在src目录下找到App.vue
和main.js
。main.js
将会做为咱们应用的入口文件而App.vue
会做为咱们应用的初始化组件。先让咱们来完善下main.js
// src/main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import App from './App'
import Home from './components/Home'
import 'bootstrap/dist/css/bootstrap.css'
Vue.use(VueRouter) Vue.use(VueResource)
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home }];
const router = new VueRouter({ routes });
/* eslint-disable no-new */
// 实例化咱们的Vue
var app = new Vue({ el: '#app', router, ...App, });
这有两个与1.0不一样的地方
1、
vue-router
路由的参数由对象统一变为了数组要注意。还有则是实例化vue的el
参数已经不能设置html
和body
了,由于在vue2
中是会替换咱们指定的标签2、咱们必须在实例化vue的时候指定渲染什么组件,之前咱们是经过路由来指定如
router.start(App, '#app')
,而在vue2中则不须要了
能够发现咱们在main.js
里使用了两个组件App.vue
和Home.vue
,稍后让咱们具体实现它们的内容。
而咱们的index.html
只须要保留<div id="app"></div>
便可,咱们的 Vue 在实例化时设置了el : '#app'
因此会替换这标签,为咱们App
组件的内容
//index.html
<div id="app"></div>
咱们的初始化就到这结束了,接下来让咱们开始建立组件。
首先咱们在 App.vue 里为咱们的应用写个顶部导航。
// src/App.vue
<template>
<div id="wrapper"> <nav class="navbar navbar-default"> <div class="container"> <a class="navbar-brand" href="#"> <i class="glyphicon glyphicon-time"></i> 计划板
</a> <ul class="nav navbar-nav"> <li><router-link to="/home">首页</router-link></li> <li><router-link to="/time-entries">计划列表</router-link></li> </ul> </div> </nav> <div class="container"> <div class="col-sm-3"> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> </div>
</template>
除了咱们的navbar
之外,咱们还须要一个.container
去放咱们其他须要展现的信息。而且在这里咱们要放一个router-view
标签,vue-router
的切换就是经过这个标签开始显现的。
在这有个与1.0不一样的地方
之前咱们能够直接经过写a标签 而后写v-link属性进行路由跳转,在 vue2 中改成了写
<router-link>
标签再写对应属性(to)进行跳转
接着,咱们须要建立一个Home.vue
做为咱们的首页
// src/components/Home.vue
<template>
<div class="jumbotron"> <h1>任务追踪</h1> <p> <strong> <router-link to="/time-entries">建立一个任务</router-link> </strong> </p> </div>
</template>
不出意外的话,你能够看见以下效果
目前咱们首页左侧还有一块空白,咱们须要它放下一个侧边栏去统计全部计划的总时间。
// src/App.vue //... <div class="container">
<div class="col-sm-3"> <sidebar></sidebar> </div> <div class="col-sm-9"> <router-view></router-view> </div> </div> //...
<script>
import Sidebar from './components/Sidebar.vue' export default { components: { 'sidebar': Sidebar }, } </script>
在Sidebar.vue
咱们须要经过 store 去获取总时间,咱们的总时间是共享的数据
// src/components/Sidebar.vue
<template>
<div class="panel panel-default"> <div class="panel-heading"> <h1 class="text-center">已有时长</h1> </div> <div class="panel-body"> <h1 class="text-center">{{ time }} 小时</h1> </div> </div>
</template>
<script> export default { computed: { time() {
return this.$store.state.totalTime } } }
</script>
而后咱们须要去建立咱们的时间跟踪列表。
// src/components/TimeEntries.vue
<template>
<div> //`v-if`是vue的一个指令 //`$route.path`是当前路由对象的路径,会被解析为绝对路径当 //`$route.path !== '/time-entries/log-time'`为`true`是显示,`false`,为不显示。 //to 路由跳转地址
<router-link v-if="$route.path !== '/time-entries/log-time'" to="/time-entries/log-time" class="btn btn-primary"> 建立
</router-link> <div v-if="$route.path === '/time-entries/log-time'"> <h3>建立</h3> </div> <hr> <router-view></router-view> <div class="time-entries"> <p v-if="!plans.length"><strong>尚未任何计划</strong></p> <div class="list-group"> <-- v-for循环,注意参数顺序为(item,index) in items --> <a class="list-group-item" v-for="(plan,index) in plans"> <div class="row"> <div class="col-sm-2 user-details"> <-- `:src`属性,这个是vue的属性绑定简写`v-bind`能够缩写为`:` 好比a标签的`href`能够写为`:href` 而且在vue的指令里就必定不要写插值表达式了(`:src={{xx}}`),vue本身会去解析 --> <img :src="plan.avatar" class="avatar img-circle img-responsive" /> <p class="text-center"> <strong> {{ plan.name }}
</strong> </p> </div> <div class="col-sm-2 text-center time-block"> <h3 class="list-group-item-text total-time"> <i class="glyphicon glyphicon-time"></i> {{ plan.totalTime }}
</h3> <p class="label label-primary text-center"> <i class="glyphicon glyphicon-calendar"></i> {{ plan.date }}
</p> </div> <div class="col-sm-7 comment-section"> <p>{{ plan.comment }}</p> </div> <div class="col-sm-1"> <button class="btn btn-xs btn-danger delete-button" @click="deletePlan(index)"> X
</button> </div> </div> </a> </div> </div> </div>
</template>
关于 template 的解释,都写在一块儿了,再看看咱们的script
// src/components/TimeEntries.vue
<script> export default { name : 'TimeEntries', computed : { plans () {
// 从store中取出数据 return this.$store.state.list } }, methods : { deletePlan(idx) {
// 稍后再来讲这里的方法 // 减去总时间 this.$store.dispatch('decTotalTime',this.plans[idx].totalTime)
// 删除该计划 this.$store.dispatch('deletePlan',idx) } } } </script>
别忘了为咱们的组件写上一些须要的样式
// src/components/TimeEntries.vue
<style> .avatar { height: 75px; margin: 0 auto; margin-top: 10px; margin-bottom: 10px; } .user-details { background-color: #f5f5f5; border-right: 1px solid #ddd; margin: -10px 0; } .time-block { padding: 10px; } .comment-section { padding: 20px; } </style>
既然咱们的数据是共享的,因此咱们须要把数据存在store
里
咱们在 src 下建立个目录为store
在store
下分别建立4个js文件actions.js
,index.js
,mutation-types.js
,mutations.js
看名字也就知道这4个分别是作啥用的了,建议你们多阅读阅读vuex
的文档,多姿式多动手实践,慢慢的也就能理解了。
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// 先写个假数据
const state = { totalTime: 0, list: [{ name : '二哲', avatar : 'https://sfault-avatar.b0.upaiyun.com/147/223/147223148-573297d0913c5_huge256', date : '2016-12-25', totalTime : '6', comment : '12月25日完善,陪女友一块儿过圣诞节须要6个小时' }] }; export default new Vuex.Store({ state, })
因为新增了页面和 store 在咱们的入口 js 文件里配置下
// src/main.js
import store from './store'
import TimeEntries from './components/TimeEntries.vue'
//...
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home },{ path : '/time-entries', component : TimeEntries, }];var app = new Vue({ el: '#app', router, store, ...App, });
不出意外的话,你能够在/time-entries
路由下看见这样的页面
经过vue-Devtools
咱们能够发现咱们的store已经构造好了而且成功从 store 获取了数据
这个比较简单咱们直接给出代码
// src/components/LogTime.vue
<template>
<div class="form-horizontal"> <div class="form-group"> <div class="col-sm-6"> <label>日期</label> <input type="date" class="form-control" v-model="date" placeholder="Date" /> </div> <div class="col-sm-6"> <label>时间</label> <input type="number" class="form-control" v-model="totalTime" placeholder="Hours" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <label>备注</label> <input type="text" class="form-control" v-model="comment" placeholder="Comment" /> </div> </div> <button class="btn btn-primary" @click="save()">保存</button> <router-link to="/time-entries" class="btn btn-danger">取消</router-link> <hr> </div>
</template>
<script> export default { name : 'LogTime', data() { return { date : '', totalTime : '', comment : '' } }, methods:{ save() {
const plan = { name : '二哲', image : 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256', date : this.date, totalTime : this.totalTime, comment : this.comment };
this.$store.dispatch('savePlan', plan)
this.$store.dispatch('addTotalTime', this.totalTime)
this.$router.go(-1) } } }
</script>
这个组件很简单就3个 input 输入而已,而后就两个按钮,保存咱们就把数据 push 进咱们 store 的列表里
LogTime
属于咱们TimeEntries
组件的一个子路由,因此咱们依旧须要配置下咱们的路由,而且利用webpack让它懒加载,减小咱们首屏加载的流量
// src/main.js
//...
const routes = [{ path : '/', component : Home },{ path : '/home', component : Home },{ path : '/time-entries', component : TimeEntries, children : [{ path : 'log-time',
// 懒加载 component : resolve => require(['./components/LogTime.vue'],resolve), }] }];
//...
在 vue2.0 中废除了使用事件的方式进行通讯,因此在小项目中咱们可使用Event Bus,其他最好都使用 vuex,本文咱们使用 Vuex 来实现数据通讯
相信你刚刚已经看见了我写了不少this.$store.dispatch('savePlan', plan)
相似这样的代码,咱们再次统一说明。
仔细思考一下,咱们须要两个全局数据,一个为全部计划的总时间,一个是计划列表的数组。
src/store/index.js
没啥太多可介绍的,其实就是传入咱们的state
,mutations
,actions
来初始化咱们的 Store。若是有须要的话咱们还可能须要建立咱们的getter
在本例中就不用了。
接着咱们看mutation-types.js
,既然想很明确了解数据,那就应该有什么样的操做看起,固然这也看我的口味哈
// src/store/mutation-types.js
// 增长总时间或者减小总时间
export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME'; export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME';
// 新增和删除一条计划
export const SAVE_PLAN = 'SAVE_PLAN'; export const DELETE_PLAN = 'DELETE_PLAN';
// src/store/mutations.js
import * as types from './mutation-types'
export default {
// 增长总时间 [types.ADD_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime + time },
// 减小总时间 [types.DEC_TOTAL_TIME] (state, time) { state.totalTime = state.totalTime - time },
// 新增计划 [types.SAVE_PLAN] (state, plan) {
// 设置默认值,将来咱们能够作登入直接读取昵称和头像 const avatar = 'https://sfault-avatar.b0.upaiyun.com/147/223/147223148-573297d0913c5_huge256'; state.list.push(
Object.assign({ name: '二哲', avatar: avatar }, plan) ) },
// 删除某计划 [types.DELETE_PLAN] (state, idx) { state.list.splice(idx, 1); } };
最后对应看咱们的actions
就很明白了
// src/store/actions.js
import * as types from './mutation-types'
export default { addTotalTime({ commit }, time) { commit(types.ADD_TOTAL_TIME, time) }, decTotalTime({ commit }, time) { commit(types.DEC_TOTAL_TIME, time) }, savePlan({ commit }, plan) { commit(types.SAVE_PLAN, plan); }, deletePlan({ commit }, plan) { commit(types.DELETE_PLAN, plan) } };
咱们的actions
其实就是去触发事件和传入参数啦
加了这三个文件后咱们的 store 终于完整了,更新下咱们的代码
// src/store/index.js 完整代码
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex);
const state = { totalTime: 0, list: [] }; export default new Vuex.Store({ state, mutations, actions })
this.$store.dispatch('savePlan', plan)
当执行了这样的方法就会调用actions.js
里的savePlan
方法,而savePlan
又会触发 mutations
里的 types.SAVE_PLAN
最后修改数据视图更新
PS:在这有个技巧就是,在
mutations
里都是用大写下划线链接,而咱们的actions
里都用小写驼峰对应。
我的理解这其实就是一个发布订阅的模式
mutation-types
记录咱们全部的事件名
mutations
注册咱们各类数据变化的方法
actions
则能够编写异步的逻辑或者是一些逻辑,再去commit
咱们的事件
若是有getter
咱们能够把一些须要处理返回的数据放在这便可,不进行业务操做
最后别忘了在咱们的main.js
里使用咱们的store
// src/store/main.js
import store from './store'
// ...
var app = new Vue({ el: '#app', router, store, ...App, });
开始体验下你本身的任务计划板吧!
经过本文,咱们能够学习到许多关于 vue 的特性。
1.了解了 vue-cli 脚手架
2.初步对 webpack 有了一些了解和认识
3.如何用 .vue 愉快的开发
4.使用 vuex 进行组件通讯
5.路由(子路由)的应用
6.使用 vue-devtools 观察咱们的数据
我的网站 :http://www.meckodo.com
github地址:https://github.com/MeCKodo/vue-tutorial
-EOF-
【活动推荐】SegmentFault 开发者大会 2016 - 杭州站即将开始,感兴趣的小伙伴赶忙报名参会!
👇 点击「阅读原文」,便可报名。