Vue 02:单页面开发基础

本文粗略讲述了Vue单页面应用开发,包括组件:状态管理模块Vuex、路由管理模块VueRouter、AJAX模块VueResource等,新建一个页面并实现跳转。

VueResource

工程中默认使用的ajax模块是axios,需要额外下载VueResource

1
$ npm install vue-resource

VueRouter

VueRouter用于管理单页面应用的页面跳转,可以实现局部页面的切换,路由配置文件为/src/router.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 配置的解析方式为:查找到路径后就停止向后解析
const routers = [{
path: '/',
meta: {
title: ''
},
component: (resolve) => require(['./views/index.vue'], resolve)
},
{path: '/index', component: require('./views/index.vue')}, // 与/一致,方便跳转到首页
{path: '/hello', component: require('./views/main/hello.vue')}, // 跳转到hello页面
{path: '*', component: require('./views/index.vue')}, // 找不到路径时,默认跳转到首页
]

export default routers

Main.js

/src/main.js为项目总配置文件,在其中引入各模块,并实例化前端应用根节点,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 全局引入模块文件和样式
import Vue from 'vue' // 引入Vue
import iView from 'iview' // 引入iView
import VueRouter from 'vue-router' // 引入VueRouter
import Routers from './router' // 引入VueRouter配置文件
import Vuex from 'vuex' // 引入Vuex
import VueResource from 'vue-resource' // 引入VueResource(新增)
import Util from './libs/util' // 引入util包
import App from './app.vue' // 引入项目入口模板
import 'iview/dist/styles/iview.css' // 引入iView样式

// Vue引用模块
Vue.use(VueRouter) // 路由模块
Vue.use(Vuex) // 状态管理
Vue.use(VueResource) // Ajax模块(新增)
Vue.use(iView) // iView组件

// VueRouter路由模块配置和实例化
const RouterConfig = {
mode: 'history',
routes: Routers
}
const router = new VueRouter(RouterConfig)

router.beforeEach((to, from, next) => {
iView.LoadingBar.start()
Util.title(to.meta.title)
next()
})

router.afterEach(() => {
iView.LoadingBar.finish()
window.scrollTo(0, 0)
})

// Vuex状态管理实例化
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {}
})

// 实例化前端根节点,声明变量vm,作为全局应用,方便后续调用
var vm = new Vue({
el: '#app', //入口元素
router: router, // 路由
store: store, // 状态
render: h => h(App) // 渲染
})

Hello World

  • 新建页面/src/views/main/hello.vue
1
2
3
4
5
6
7
8
9
10
<template>
<div id="hello">
Hello World!
</div>
</template>
<script>
export default {
name: 'hello', // name属性用于Vue框架报错时,显示错误模块名
}
</script>
  • 新建样式文件/src/styles/main.less和/src/styles/variables.less,前者用于全局样式,后者用于定义全局less变量
1
2
3
4
5
6
7
8
9
10
// variables.less
@global-color: #ffffff;

// main.less
@import '../styles/variables.less';

html, body {
height: 100%;
background-color: @global-color
}
  • 修改index.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<style lang="less" scoped>
@import '../styles/main.less';
</style>
<template>
<div>
<!-- 绑定goHello方法 -->
<button @click="goHello">Go to Hello</button>
</div>
</template>
<script>
export default {
methods: {
// 绑定按钮的点击事件
goHello: function () {
// 跳转到/hello,在/src/router.js中指向/views/main/hello.vue
this.$router.push({
path: '/hello'
}),

this.$http.get('/dist/data/ajax.json').then((response) => {
// 响应成功回调
console.log("Success message: " + response.body.message)
}, (response) => {
// 响应错误回调
console.log("Failure message: " + response.body.message)
});
}
}
}
</script>

VueResource

  • VueResource负责与后端进行Ajax请求交互,基本用法如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export default {
methods: {
ajaxReq: function () {

// 基本结构为this.$http.get(url).then(success, failure)
// success和failure使用Lambda表达式,好处是不会改变函数内部的上下文
var me = this;
this.$http.get('/dist/data/ajax.json').then((response) => {

// 由于使用Lambda表达式,上下文未变化
console.log(this === me)

// 响应成功回调
console.log("Success message: " + response.body.message)

}, (response) => {

// 响应错误回调
console.log("Failure message: " + response.body.message)

});
}
}
}
  • 调用方法有两种
1
2
Vue.$http.get()  // 全局
this.$http.get() // 局部
  • 除了get,还有下列REST方法
1
2
3
4
5
6
7
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
  • options包含以下属性
1
2
3
4
5
6
7
8
9
10
11
url				string				请求的URL
method string 请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法
body Object,FormData string request body
params Object 请求的URL参数对象
headers Object request header
timeout number 单位为毫秒的请求超时时间 (0 表示无超时时间)
before function(request) 请求发送前的处理函数,类似于jQuery的beforeSend函数
progress function(event) ProgressEvent回调处理函数
credentials boolean 表示跨域请求时是否需要使用凭证
emulateHTTP boolean 发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override
emulateJSON boolean 将request body以application/x-www-form-urlencoded content type发送
  • response包含以下属性和方法
1
2
3
4
5
6
7
8
9
方法			类型			描述
text() string 以string形式返回response body
json() Object 以JSON对象形式返回response body
blob() Blob 以二进制形式返回response body
属性 类型 描述
ok boolean 响应的HTTP状态码在200~299之间时,该属性为true
status number 响应的HTTP状态码
statusText string 响应的状态文本
headers Object 响应头
分享到