Vue.js2.0从入门到放弃---入门实例(三)

xiaoxiao2021-02-28  135

http://blog.csdn.net/u013182762/article/details/53488870

已经有几周没有更新博客了,最近自己也在学习就没有能及时抽身来写博客。

今天就来简单说一下vue-resource,这是vue的一个与服务器端通信的HTTP插件,用来从服务器端请求数据。话不多说,直接上干货吧。

这里PS一下,有人反映之前的代码下载下来,运行会报错而且会有上百个之多,这是因为在我初始化项目的时候没有启用eslint,eslint是用来检测代码风格的,我是觉得格式要求严的有点过分,所以禁用了eslint。如果对eslint感兴趣的朋友,可以看 eslint的官网 了解一下格式的要求和一些相应的配置。

我们主要来了解一下以下内容:

模拟服务端返回数据用vue-resource向服务器请求数据

模拟服务器返回数据

我们用vue-cli创建的项目中,已经给我们提供了模拟服务器端返回数据的地方和接口。如下图所示,在项目目录的build目录下,有一个dev-server.js,在这个文件中,我们就可以来做一些模拟数据的工作。

1、准备一个data.json文件

在项目根目录下,新建一个data.json。这个文件里的内容就是我们要模拟的服务端返回的数据。 data.json的内容如下: [javascript]  view plain  copy {       "books": [           { "price""111.00""title""语文""img""http://imgsrc.baidu.com/forum/w=580/sign=688d19b6422309f7e76fad1a420f0c39/0e143912b31bb051dfdebf0a327adab44bede0f9.jpg" },           { "price""123.00""title""数学""img""http://shopimg.kongfz.com.cn/20130826/1746508/1746508YTGtm0_b.jpg"},           { "price""113.00""title""英语""img""http://www.shiyi910.com/UploadFiles/2014-01/170/2014011322414554305.jpg"},           { "price""112.00""title""物理""img""http://f.hiphotos.baidu.com/zhidao/wh=450,600/sign=b62ac53d4b36acaf59b59ef849e9a126/f603918fa0ec08fa2cf895a359ee3d6d55fbda3e.jpg"}       ]   }   这里,books字段里的每一个对象表示一本书的信息。

2、“写接口”

修改dev-server.js文件,在大概第19行左右的  var app = express()之后,添加上如下内容 [javascript]  view plain  copy var appData = require('../data.json')   var books = appData.books      var apiRoutes = express.Router()   apiRoutes.get('/books'function(req, res){     res.json({       data: books     })   })      app.use('/api', apiRoutes)   简单说明一下,这段代码就是通过请求醒目根目录下的data.json文件,拿到文件的内容并赋值给appData变量,取到里面的books字段内容保存在books变量中。然后,通过express提供的Router对象,以及Router对象的一些方法(这里是get方法)来设置请求的路径,以及请求成功后的回调函数来处理要返回给请求端的数据。最后,我们要“使用”这个Router对象,为了统一管理api接口,我们在要请求的路由前边都加上‘api/’来表明这个路径是专门用来提供api数据的。在这个“接口”中,当我们访问“http://localhost:8080/api/books”路径的时候,就会返回data.json里的books对象给我们。 这里我们先来简单验证一下是否能成功返回数据,打开命令行,cd到当前项目目录,运行 npm run dev ,等项目运行成功之后,在浏览器地址栏输入http://localhost:8080/api/books,看到如下图所示,数据正常返回,OK!“接口”就开发完成了。 PS:在你的浏览器上可能看到的是没有经过格式化的数据,我的浏览器上装了一个json格式化的插件,这不是重点,重点是“接口”正常工作了,不是吗 。

用vue-resource向服务器请求数据

1、安装vue-resource

打开命令行,cd到项目目录,运行  npm install vue-resource --save或者  cnpm install vue-resource --save,等待安装完成即可。

2、在main.js里导入并使用vue-resource

修改main.js如下 [javascript]  view plain  copy // main.js      // 导入Vue,这个是必需的,在使用Vue之前,必须先导入   import Vue from 'vue'      // 导入 vue-router,并使用   import VueRouter from 'vue-router'   Vue.use(VueRouter)      // 导入 vue-resource,并使用   import VueResource from 'vue-resource'   Vue.use(VueResource)      // 导入 pages 下的 Home.vue    import Home from './pages/Home'   import Detail from './pages/Detail'      // 定义路由配置   const routes = [       {           path: '/',           component: Home       },       {           path: '/detail',           component: Detail       }   ]      // 创建路由实例   const router = new VueRouter({       routes   })      // 创建 Vue 实例   new Vue({     el: '#app',     data(){       return {           transitionName: 'slide'       }     },     router,     watch: {       // 监视路由,参数为要目标路由和当前页面的路由       '$route' (to, from){           const toDepth = to.path.substring(0, to.path.length-2).split('/').length           // 官方给出的例子为 const toDepth = to.path.split('/').length 由于现在只有两个路由路径'/'和'/detail'           // 按照官方给的例子,这两个路由路径深度都为 2 ,所以,这里稍作调整,不知道有什么不妥           // 但目前在这个demo中能正常运行,如果知道更好的方法,欢迎留言赐教           const fromDepth = from.path.substring(0, from.path.length-2).split('/').length           this.transitionName = toDepth < fromDepth ? 'slide_back' : 'slide'           // 根据路由深度,来判断是该从右侧进入还是该从左侧进入       }     }   })  

3、修改Home.vue和List.vue来接收服务端返回的数据

Home.vue修改如下: [html]  view plain  copy <!-- Home.vue -->   <template>       <div class="container">           <!-- 由于html不区分大小写,所以js中驼峰命名方式在html中要改成用短横线连接的形式 -->           <home-header></home-header>           <div class="content">               <ul class="cont_ul">                   <list                       v-for="item in items"                       :price="item.price"                       :title="item.title"                       :img="item.img">                   <!-- 通过v-bind(简写为“:”)绑定props来从父组件给子组件传值 -->                   </list>               </ul>           </div>       </div>   </template>   <style>       .container {           max-width: 640px;           margin: 0 auto;           overflow-x: hidden;       }       .cont_ul {           padding-top: 0.05rem;           margin: 0 -0.12rem;       }       .cont_ul:after {           content: "";           display: block;           width: 0;           height: 0;           clear: both;       }   </style>   <script>       // 导入要用到的子组件       import HomeHeader from '../components/HomeHeader'       import List from '../components/List'       export default {           data () {               return {                   items: []               }           },           // 在components字段中,包含导入的子组件           components: {               HomeHeader,               List           },           // 在组件创建完成时,执行的钩子函数           created (){               // 在main.js里导入并使用vue-resource之后,就可以通过this.$http来使用vue-resource了,这里我们用到了get方法               this.$http.get('/api/books').then((data) => {                   // 由于请求成功返回的是Promise对象,我们要从data.body.data拿到books数组                   this.items = data.body.data;               })           }       }   </script>   List.vue修改如下: [html]  view plain  copy <!-- List.vue -->   <template>       <li class="sec_li">           <router-link to="/detail" class="lp_li_a">               <div class="lp_li_imgWrap">                   <img :src="img" alt="">               </div>               <p class="lp_li_name">{{ title }}</p>               <p class="lp_li_price">¥{{ price }}元</p>           </router-link>       </li>   </template>      <style scoped>       .sec_li {           float: left;           width: 50%;           margin-bottom: 0.1rem;       }       .lp_li_a {           display: block;           padding: 0.3rem 0;           margin: 0 0.05rem;           text-align: center;           background: #fff;       }       .lp_li_imgWrap {           padding: 0.24rem 0;       }       .lp_li_imgWrap > img {           width: auto;           height: 2.3rem;       }       .lp_li_name {           height: 0.5rem;           line-height: 0.5rem;           font-size: 16px;           color: #333;       }       .lp_li_price {           height: 0.5rem;           line-height: 0.5rem;           font-size: 16px;           color: #fb3b3b;       }   </style>      <script>       export default {           // 接收父组件传过来的以下几个属性           props: ['price', 'title', 'img'],       }   </script>   然后,再回到浏览器,应该会看到如下图的效果了。 搞定!数据成功接入,可以来杯咖啡放松一下,回味一下整个过程的实现了。 还有一个“/detail”接口,就是每本书的详情,我着急下班,就先不写了。前面是我抛砖,后边的引玉部分,你可以自己尝试着来实现,你可以的! 我要下班了,如果没有练习源码的同学,看上一篇博客,里面有github地址。好了,撤!
转载请注明原文地址: https://www.6miu.com/read-69594.html

最新回复(0)