怎么vue router push跳转不支持push 方法

Vue.js 快速入门
Vue.js 快速入门
什么是Vue.js
vue是法语中视图的意思,Vue.js是一个轻巧、高性能、可组件化的MVVM库,同时拥有非常容易上手的API。作者是,写下这篇文章时vue.js版本为1.0.7
我推荐使用sublime text作为编辑器,关于这个编辑器可以看我这篇文章。在package control中安装
Vuejs Snippets
Vue Syntax Highlight
推荐使用npm管理,新建两个文件app.html,app.js,为了美观使用bootstrap,我们的页面模板看起来是这样:
&!DOCTYPE html&
&html lang="en"&
&meta charset="UTF-8"&
&title&Document&/title&
&link rel="stylesheet" type="text/css" href="/bootstrap/3.3.5/css/bootstrap.min.css"&
&div class="container"&
&div class="col-md-6 col-md-offset-3"&
&h1&Vue demo&/h1&
&div id="app"&
使用npm安装:
npm install vue
当然你也可以在github上clone最新的版本并作为单文件引入,或者使用CDN:
http://cdn.jsdelivr.net/vue/1.0.7/vue.min.js
/ajax/libs/vue/1.0.7/vue.min.js
HelloWorld
动手写第一个Vue.js 应用吧。
&div id="app"&
&div&{{message}}&/div&
&input type="text" v-model="message"&
el:'#app',
message:'hello vue.js.'
创建Vue实例
在使用Vue.js之前,我们需要先像这样实例化一个Vue对象:
双向数据绑定
就像HelloWorld展示的那样,app.html是view层,app.js是model层,通过vue.js(使用v-model这个指令)完成中间的底层逻辑,实现绑定的效果。改变其中的任何一层,另外一层都会改变。
相信你也注意到了,通过{{value}}的形式就能取到value的值,并与value进行绑定。HelloWorld中改变input中的值时相应也改变了app.js中的message,从而{{message}}也得到改变。上面的代码改为这样:
{{*message}}
则message不会随着数据的改变而更新。同时还支持一些简单的表达式:
{{message + 'vue is awesome'}}
{{ message.split('').reverse().join('') }}
常用的指令
v-model可用于一些表单元素,常见的input,checkbox,radio,select:
&select v-model="selected" multiple&
&option selected&A&/option&
&option&B&/option&
&option&C&/option&
&span&Selected: {{ selected | json }}&/span&
列表渲染在实际开发中非常常见,vue.js使用v-for这个指令就能完成,v-for取代了1.0以前版本中的v-repeat。在app.js中准备一些数据:
el: '#app',
author: '',
author: '曹雪芹',
name: '红楼梦',
price: 32.0
author: '施耐庵',
name: '水浒传',
price: 30.0
author: '罗贯中',
name: '三国演义',
price: 24.0
author: '吴承恩',
name: '西游记',
price: 20.0
在data里我们设置了两个数据book和book[] books,在app.html中我们只要这样就能获取到数据了:
&tr v-for="book in books "&
&td&{{book.id}}&/td&
&td&{{book.name}}&/td&
&td&{{book.author}}&/td&
&td&{{book.price}}&/td&
如果你比较细心的话,在数据还未加载完时是会有闪烁的情况出现,解决方法也很简单,使用v-cloak,然后定义css:
[v-cloak] { display: none }
vue.js通过v-on完成事件处理与绑定,比如为一个button绑定click事件,我们就可以这么写:
&button v-on:click="doSomething"&doSomething&/button&
也可以缩写:
&button @click="doSomething"&doSomething&/button&
我们需要为v-on传入事件参数,然后在vue的实例中声明doSomething这个方法就可以调用了:
el: '#app',
methods: {
doSomething: function () {
接着上面书的例子,我们用v-model绑定form:
&div id="add-book"&
&legend&添加书籍&/legend&
&div class="form-group"&
&label for=""&书名&/label&
&input type="text" class="form-control" v-model="book.name"&
&div class="form-group"&
&label for=""&作者&/label&
&input type="text" class="form-control" v-model="book.author"&
&div class="form-group"&
&label for=""&价格&/label&
&input type="text" class="form-control" v-model="book.price"&
&button class="btn btn-primary btn-block" v-on:click="addBook()"&添加&/button&
在app.js中增加我们的addBook方法:
methods: {
addBook: function() {
//计算书的id
this.book.id = this.books.length + 1;
this.books.push(this.book);
//将input中的数据重置
this.book = '';
我们再健全一下功能,增加一个删除按钮:
&button type="button" class="btn btn-danger" @click="delBook(book)"&删除&/button&
delBook方法:
delBook:function(book){
this.books.$remove(book);
vue.js为数组扩展了$remove方法,查找并删除我们作为参数传递过去的book。
v-if/v-else/v-show
顾名思义,v-if用于条件判断,和v-else是一对。用法也很简单,下面的代码是将id为偶数的操作按钮换个样式:
&template v-if="book.id%2==0"&
&td class="text-right"&
&button type="button" class="btn btn-success" @click="delBook(book)"&删除&/button&
&/template&
&template v-else&
&td class="text-right"&
&button type="button" class="btn btn-danger" @click="delBook(book)"&删除&/button&
&/template&
这里用到了&template&标签,用于包含多个元素,当元素只有一个时,直接在元素上用v-if即可:
&h1 v-if="ok"&Yes&/h1&
&h1 v-else&No&/h1&
v-show作用与v-if类似,不同的是v-show的元素会始终渲染并保持在 DOM 中,且v-show不支持&template&标签。
与Linux中的管道类似,vue.js也使用的是|:
{{message | uppercase}}
这样就能输出message的大写了,过滤器也能串联在一起使用:
{{message | reverse | uppercase}}
这里reverse并不是内建的过滤器,我们可以用Vue.filter自定义:
Vue.filter('reverse', function (value) {
return value.split('').reverse().join('')
过滤器支持接收参数,比较常用的是orderBy [param]和filterBy [param],现在我们为表格增加自定义排序的功能,为表头绑定click事件:
&th class="text-right" @click="sortBy('id')"&序号&/th&
&th class="text-right" @click="sortBy('name')"&书名&/th&
&th class="text-right" @click="sortBy('author')"&作者&/th&
&th class="text-right" @click="sortBy('price')"&价格&/th&
想sortBy传递列的参数,定义sortBy和data:
sortparam: ''
sortBy: function(sortparam) {
this.sortparam =
添加过滤器:
&tr v-for="book in books | orderBy sortparam"&
计算属性可以帮助我们完成一些复杂的逻辑计算,比如我们需要添加一个书的总价,在vue实例中添加computed:
computed: {
sum: function() {
var result = 0;
for (var i = 0; i & this.books. i++) {
result = Number(this.books[i].price) +
在app.html中使用插值表达式:
vue-resource
vue-resource作为vue插件的形式存在,通过 XMLHttpRequest 或 JSONP 发起请求并处理响应。在开发中也非常常见,现在我们用vue-resource来请求books:
和vue类似:
npm install vue-resource --save
如果你的项目遵循CommonJS:
var Vue = require('vue');
Vue.use(require('vue-resource'));
也可以直接引入单文件或者CDN。
在vue中新增ready对象,当页面加载完成时就去请求:
el: '#app',
ready: function() {
this.$http.get('book.json', function(data) {
this.$set('books', data);
}).error(function(data, status, request) {
console.log('fail' + status + "," + request);
为了演示,这里将json格式的数据保存在book.json中,这段数据你可以直接使用JSON.stringify()得到:
[{"id":1,"author":"曹雪芹","name":"红楼梦","price":32},{"id":2,"author":"施耐庵","name":"水浒传","price":30},{"id":"3","author":"罗贯中","name":"三国演义","price":24},{"id":4,"author":"吴承恩","name":"西游记","price":20}]
接下来你需要将app.html中运行在一个服务器中,否则由于浏览器安全的限制,是无法直接读取的,如果你嫌麻烦可以用这个参数启动chrome。
.\chrome.exe --allow-file-access-from-files
如果你使用了npm,想要启动一个服务器就太简单了:
npm install http-server -g
//在当前目录
http-server
//然后访问localhost:8080/app.html
post的语法也很简单:
this.$http.post(url,postdata,function callback)
在使用的时候遇到一个小坑,这个$http请求和jquery的ajax还是有点区别,这里的post的data默认不是以form data的形式,而是request payload。解决起来也很简单:
在vue实例中添加headers字段:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
后来翻了下vue-resource的源码,发现有更加简单的做法:
Vue.http.options.emulateJSON =
这里只简单介绍下,详细的文档请大家移步吧。
vue.js目前还有众多的插件,详情看。
这里简单介绍了下vue.js的基本用法,但只仅仅介绍了一小部分作为库使用的内容,想了解更多vue.js的内容,还是多多关注vue.js的,所用的例子我也分享了,可以在这里并运行结果。
作者:FullStackDeveloper
原文地址:
分享即可 +1积分
请登录后,发表评论
评论(Enter+Ctrl)
评论加载中...
评论加载中...
页面重构设计
这位童鞋很懒,什么也没有留下~~!
作者的热门手记
Copyright (C)
All Rights Reserved | 京ICP备 号-22002人阅读
vue.js(32)
本文的主要内容如下:
介绍vue-resource的特点介绍vue-resource的基本使用方法基于this.$http的增删查改示例基于this.$resource的增删查改示例基于inteceptor实现请求等待时的loading画面基于inteceptor实现请求错误时的提示画面
本文11个示例的源码已放到GitHub,如果您觉得本篇内容不错,请点个赞,或在GitHub上加个星星!
GitHub Source
本文的所有示例如下:
http get示例http jsonp示例http post示例http put示例http delete示例resource get示例resource save示例(HTTP POST)resource update示例(HTTP PUT)resource remove示例(HTTP DELETE)inteceptor示例1——ajax请求的loading界面inteceptor实例2——请求失败时的提示对话框
各位在阅读这篇文章的内容时,可以先尝试该列表的最后两个示例,这两个示例综合使用了this.$http和inteceptor。
vue-resource特点
vue-resource插件具有以下特点:
vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
2. 支持主流的浏览器
和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。
3. 支持Promise API和URI Templates
Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。
URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。
4. 支持拦截器
拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。
vue-resource使用
引入vue-resource
&script src=&js/vue.js&&&/script&
&script src=&js/vue-resource.js&&&/script&
引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http。
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:
// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
// Lambda写法
this.$http.get('/someUrl', [options]).then((response) =& {
// 响应成功回调
}, (response) =& {
// 响应错误回调
PS:做过.NET开发的人想必对Lambda写法有一种熟悉的感觉。
支持的HTTP方法
vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:
get(url, [options])head(url, [options])delete(url, [options])jsonp(url, [options])post(url, [body], [options])put(url, [body], [options])patch(url, [body], [options])
除了jsonp以外,另外6种的API名称是标准的HTTP方法。当服务端使用REST API时,客户端的编码风格和服务端的编码风格近乎一致,这可以减少前端和后端开发人员的沟通成本。
客户端请求方法
服务端处理方法
this.$http.get(...)
this.$http.post(...)
this.$http.put(...)
this.$http.delete(...)
options对象
发送请求时的options选项对象包含以下属性:
请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法
Object,FormDatastring
request body
请求的URL参数对象
request header
单位为毫秒的请求超时时间 (0 表示无超时时间)
function(request)
请求发送前的处理函数,类似于jQuery的beforeSend函数
function(event)
ProgressEvent回调处理函数
credientials
表示跨域请求时是否需要使用凭证
emulateHTTP
发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override
emulateJSON
将request body以application/x-www-form-urlencoded content type发送
emulateHTTP的作用
如果Web服务器无法处理PUT, PATCH和DELETE这种REST风格的请求,你可以启用enulateHTTP现象。启用该选项后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实际的HTTP方法。
Vue.http.options.emulateHTTP =
emulateJSON的作用
如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。启用该选项后,请求会以application/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。
Vue.http.options.emulateJSON =
response对象
response对象包含以下属性:
以string形式返回response body
以JSON对象形式返回response body
以二进制形式返回response body
响应的HTTP状态码在200~299之间时,该属性为true
响应的HTTP状态码
statusText
响应的状态文本
注意:本文的vue-resource版本为v0.9.3,如果你使用的是v0.9.0以前的版本,response对象是没有json(), blob(), text()这些方法的。
提示:以下示例仍然沿用上一篇的组件和WebAPI,组件的代码和页面HTML代码我就不再贴出来了。
var demo = new Vue({
el: '#app',
gridColumns: ['customerId', 'companyName', 'contactName', 'phone'],
gridData: [],
apiUrl: 'http://211.149.193.19:8080/api/customers'
ready: function() {
this.getCustomers()
methods: {
getCustomers: function() {
this.$http.get(this.apiUrl)
.then((response) =& {
this.$set('gridData', response.data)
.catch(function(response) {
console.log(response)
这段程序的then方法只提供了successCallback,而省略了errorCallback。
catch方法用于捕捉程序的异常,catch方法和errorCallback是不同的,errorCallback只在响应失败时调用,而catch则是在整个请求到响应过程中,只要程序出错了就会被调用。
在then方法的回调函数内,你也可以直接使用this,this仍然是指向Vue实例的:
getCustomers: function() {
this.$http.get(this.apiUrl)
.then((response) =& {
this.$set('gridData', response.data)
.catch(function(response) {
console.log(response)
为了减少作用域链的搜索,建议使用一个局部变量来接收this。
getCustomers: function() {
this.$http.jsonp(this.apiUrl).then(function(response){
this.$set('gridData', response.data)
var demo = new Vue({
el: '#app',
show: false,
gridColumns: [{
name: 'customerId',
isKey: true
name: 'companyName'
name: 'contactName'
name: 'phone'
gridData: [],
apiUrl: 'http://211.149.193.19:8080/api/customers',
ready: function() {
this.getCustomers()
methods: {
closeDialog: function() {
this.show = false
getCustomers: function() {
var vm = this
vm.$http.get(vm.apiUrl)
.then((response) =& {
vm.$set('gridData', response.data)
createCustomer: function() {
var vm = this
vm.$http.post(vm.apiUrl, vm.item)
.then((response) =& {
vm.$set('item', {})
vm.getCustomers()
this.show = false
updateCustomer: function() {
var vm = this
vm.$http.put(this.apiUrl + '/' + vm.item.customerId, vm.item)
.then((response) =& {
vm.getCustomers()
Delete请求
deleteCustomer: function(customer){
var vm = this
vm.$http.delete(this.apiUrl + '/' + customer.customerId)
.then((response) =& {
vm.getCustomers()
使用resource服务
vue-resource提供了另外一种方式访问HTTP——resource服务,resource服务包含以下几种默认的action:
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
resource对象也有两种访问方式:
全局访问:Vue.resource实例访问:this.$resource
resource可以结合URI Template一起使用,以下示例的apiUrl都设置为{/id}了:
apiUrl: 'http://211.149.193.19:8080/api/customers{/id}'
使用get方法发送GET请求,下面这个请求没有指定{/id}。
getCustomers: function() {
var resource = this.$resource(this.apiUrl)
resource.get()
.then((response) =& {
vm.$set('gridData', response.data)
.catch(function(response) {
console.log(response)
使用save方法发送POST请求,下面这个请求没有指定{/id}。
createCustomer: function() {
var resource = this.$resource(this.apiUrl)
resource.save(vm.apiUrl, vm.item)
.then((response) =& {
vm.$set('item', {})
vm.getCustomers()
this.show = false
使用update方法发送PUT请求,下面这个请求指定了{/id}。
updateCustomer: function() {
var resource = this.$resource(this.apiUrl)
resource.update({ id: vm.item.customerId}, vm.item)
.then((response) =& {
vm.getCustomers()
{/id}相当于一个占位符,当传入实际的参数时该占位符会被替换。
例如,{ id: vm.item.customerId}中的vm.item.customerId为12,那么发送的请求URL为:
http://211.149.193.19:8080/api/customers/12
DELETE请求
使用remove或delete方法发送DELETE请求,下面这个请求指定了{/id}。
deleteCustomer: function(customer){
var resource = this.$resource(this.apiUrl)
resource.remove({ id: customer.customerId})
.then((response) =& {
vm.getCustomers()
使用inteceptor
拦截器可以在请求发送前和发送请求后做一些处理。
Vue.http.interceptors.push((request, next) =& {
// 请求发送前的处理逻辑
next((response) =& {
// 请求发送后的处理逻辑
// 根据请求的状态,response参数会返回给successCallback或errorCallback
return response
在response返回给successCallback或errorCallback之前,你可以修改response中的内容,或做一些处理。
例如,响应的状态码如果是404,你可以显示友好的404界面。
如果不想使用Lambda函数写法,可以用平民写法:
Vue.http.interceptors.push(function(request, next) {
// 请求发送前的处理逻辑
next(function(response) {
// 请求发送后的处理逻辑
// 根据请求的状态,response参数会返回给successCallback或errorCallback
return response
之前的CURD示例有一处用户体验不太好,用户在使用一些功能的时候如果网络较慢,画面又没有给出反馈,用户是不知道他的操作是成功还是失败的,他也不知道是否该继续等待。
通过inteceptor,我们可以为所有的请求处理加一个loading:请求发送前显示loading,接收响应后隐藏loading。
具体步骤如下:
1.添加一个loading组件
&template id=&loading-template&&
&div class=&loading-overlay&&
&div class=&sk-three-bounce&&
&div class=&sk-child sk-bounce1&&&/div&
&div class=&sk-child sk-bounce2&&&/div&
&div class=&sk-child sk-bounce3&&&/div&
&/template&
2.将loading组件作为另外一个Vue实例的子组件
var help = new Vue({
el: '#help',
showLoading: false
components: {
'loading': {
template: '#loading-template',
3.将该Vue实例挂载到某个HTML元素
&div id=&help&&
&loading v-show=&showLoading&&&/loading&
4.添加inteceptor
Vue.http.interceptors.push((request, next) =& {
loading.show = true
next((response) =& {
loading.show = false
return response
当用户在画面上停留时间太久时,画面数据可能已经不是最新的了,这时如果用户删除或修改某一条数据,如果这条数据已经被其他用户删除了,服务器会反馈一个404的错误,但由于我们的put和delete请求没有处理errorCallback,所以用户是不知道他的操作是成功还是失败了。
你问我为什么不在每个请求里面处理errorCallback,这是因为我比较懒。这个问题,同样也可以通过inteceptor解决。
1. 继续沿用上面的loading组件,在#help元素下加一个对话框
&div id=&help&&
&loading v-show=&showLoading& &&/loading&
&modal-dialog :show=&showDialog&&
&header class=&dialog-header& slot=&header&&
&h1 class=&dialog-title&&Server Error&/h1&
&div class=&dialog-body& slot=&body&&
&p class=&error&&Oops,server has got some errors, error code: {{errorCode}}.&/p&
&/modal-dialog&
2.给help实例的data选项添加两个属性
var help = new Vue({
el: '#help',
showLoading: false,
showDialog: false,
errorCode: ''
components: {
'loading': {
template: '#loading-template',
3.修改inteceptor
Vue.http.interceptors.push((request, next) =& {
help.showLoading = true
next((response) =& {
if(!response.ok){
help.errorCode = response.status
help.showDialog = true
help.showLoading = false
return response
vue-resource是一个非常轻量的用于处理HTTP请求的插件,它提供了两种方式来处理HTTP请求:
使用Vue.http或this.$http使用Vue.resource或this.$resource
这两种方式本质上没有什么区别,阅读vue-resource的源码,你可以发现第2种方式是基于第1种方式实现的。
inteceptor可以在请求前和请求后附加一些行为,这意味着除了请求处理的过程,请求的其他环节都可以由我们来控制。
参考链接:/vuejs/vue-resource/tree/master/docs
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:27355次
排名:千里之外
原创:38篇
转载:94篇
评论:11条
(4)(31)(50)(19)(10)(9)(1)(14)

我要回帖

更多关于 vue router.push 的文章

 

随机推荐