在上一节《vue+vue-router+axios+element-ui构建vue实战项目之五(配置axios api接口调用)》中,咱们配置完成axios后,成功访问https://unpkg.com/axios@0.18.0/dist/axios.min.js接口并返回了数据。css
好,这节开始,咱们来写点“真”东西。html
很少说,直接上代码vue
1 <template> 2 <div> 3 <ul> 4 <li v-for="item in getList"> 5 <span>{{item.create_at}}</span> 6 <router-link :to="'/content/'+item.id" :target="'_blank'"> 7 {{item.title}} 8 </router-link> 9 </li> 10 </ul> 11 </div> 12 </template> 13 <script> 14 export default { 15 data () { 16 return { 17 getList: [] 18 } 19 }, 20 mounted () { 21 this.getTopics() 22 }, 23 methods: { 24 getTopics (){ 25 this.$http.get('/topics') 26 .then(res => { 27 console.log(res) 28 res.data.success && (this.getList = res.data.data) 29 }) 30 .catch(err =>{ 31 console.log(err) 32 }) 33 } 34 } 35 } 36 </script> 37 <style lang="scss"> 38 @import "../style/style"; 39 </style>
src/style/style.scss代码node
1 ul>li{list-style: decimal}
浏览器显示效果,如图ios
这里要说一下,为何接口只写了“/topics”,而完整的接口路径为“https://cnodejs.org/api/v1/topics”es6
1 this.$http.get('/topics') 2 .then(res => { 3 console.log(res) 4 res.data.success && (this.getList = res.data.data) 5 }) 6 .catch(err =>{ 7 console.log(err) 8 })
通常咱们作开发的时候,接口的路径基原本自同一个地址,若是每次都这么写的话,重复工做太多,而且后续若是接口变了,修改起来也麻烦。vue-router
因此,咱们须要在main.js里面添加一句:element-ui
1 //设置全局访问接口 2 axios.defaults.baseURL = 'https://cnodejs.org/api/v1'
后续,调用来自同一个地方的接口时,只须要写接口的方法便可。axios
可能有人要问,代码中 res => {} 是什么意思,这是es6的箭头函数,上面的代码等同于api
1 this.$http.get('/topics') 2 .then(function (res) { 3 console.log(res) 4 res.data.success && (this.getList = res.data.data) 5 }) 6 .catch(function (err) { 7 console.log(err) 8 })
若是对es6有其余疑问,能够移步阮一峰老师的《ES6入门》教程,里面有详细介绍。
因为有了前面几篇文章的积累,这里就比较好理解了。
咱们从接口拿到了 res.data
的数据,让咱们本身定义的 this.getList
等于这个数据,而后咱们在模板中就能够用 getList 进行渲染了。
这里体现了 vue
的数据双向绑定的特性。
以下面的图片所示,因为拿到的数据是一个标准的时间格式,直接渲染在页面上,这个效果不是很理想。
所以,咱们能够把时间给处理一下,而后再渲染出来。
编写 src/utils/index.js 文件
1 export default { 2 //格式化日期 3 formatDate (str){ 4 let result = '' 5 const date = new Date(str).toLocaleDateString() 6 const hour = new Date(str).getHours() 7 const minute = new Date(str).getMinutes() 8 const second = new Date(str).getSeconds() 9 result = date.replace(/\//g,'-') + ' ' + hour + ':' + minute + ':' + second 10 return result 11 } 12 13 }
写好代码以后,咱们保存文件,可是此时,咱们还不能使用咱们的这个方法函数,咱们必须在 main.js
中将咱们的方法函数给绑定上。
以下代码:
1 引用utils工具文件 2 import utils from './utils' 3 //全局注册utils 4 Vue.prototype.$utils = utils
好了,这样,咱们写的这个函数,就能够随便被咱们调用了。
咱们再来修改一下咱们上面的 index.vue
中的代码,将 span 调整为:
1 <span>{{$utils.formatDate(item.create_at)}}</span>
按照上面的步骤修改代码后,咱们再来看结果
好,咱们已经看到,时间已经搞好了。
不知道你们有没有发现,咱们在 script 区域,引用一个函数是使用 this.getTopics或者 this.getList 这样的代码引用的。可是在 template 中,咱们是不加 this 的。
在 js 中,关于 this 的论文就不少,这里不深刻讲解了,具体的你们去看vue的官方文档。
好,列表已经渲染出来了。下一节,咱们渲染content.vue文件。
若是文章中存在错误的地方,麻烦请你们在评论中指正,以避免误人子弟,谢谢!