码迷,mamicode.com
首页 > Windows程序 > 详细

Vue架构学习笔记之条件循环、API接口访问

时间:2018-04-13 17:51:24      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:blank   class   bin   doctype   vue   api接口   rom   .com   htm   

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Test</title>
    <meta charset="utf-8">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
  </head>
  <body>
  		<!-- <div id="app-3">
  			<p v-if="seen">look at me</p>
  		</div> -->
  		<div id="app-4">
        <ol>
          <li v-for="todo in todos">
            {{ todo.quantity }} {{ todo.name}}
            <span v-if="todo.quantity === 0">
                - OUT OF STOCK
            </span>
          </li>
        </ol>
        <h2>Total Inventory: {{ totalProducts }}</h2>
      </div>
  		<!-- <script src="vue.js"></script> -->
  		<script type="text/javascript">
  			// var app3 = new Vue({
  			// 	el: ‘#app-3‘,
  			// 	data: {
  			// 		seen : true
  			// 	}
  			// })
  			var app4 = new Vue({
          el: ‘#app-4‘,
          data: {
            todos: []
          },
          computed: {
            totalProducts () {
              return this.todos.reduce((sum, todo) => {
                return sum + todo.quantity
              }, 0 )
            }
          },
          created () {
            fetch(‘https://api.myjson.com/bins/74l63‘)
            .then(response => response.json())
            .then(json => {
              this.todos = json.products
            })
          }
        })
  		</script>
  </body>
  </html>

  先贴代码,上面主要功能是Vue中的v-for 的条件循环 、v-if 条件判断 以及API接口JSON数据接收。

如图:

技术分享图片

其中计算总数函数为

computed: {
            totalProducts () {
              return this.todos.reduce((sum, todo) => {
                return sum + todo.quantity
              }, 0 )
            }
          },

 接收数据:

created () {
            fetch(‘https://api.myjson.com/bins/74l63‘)
            .then(response => response.json())
            .then(json => {
              this.todos = json.products
            })
          }

 fetch是基于Promise的,异步操作更友好,解决了多步回调,让代码更优雅友好。

 网络交互推荐 axios.js (Vue官网推荐),因为Vue框架是非入侵性框架,并不限制我们使用ajax框架。

axios全攻略

Vue架构学习笔记之条件循环、API接口访问

标签:blank   class   bin   doctype   vue   api接口   rom   .com   htm   

原文地址:https://www.cnblogs.com/BigStupid/p/8821595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!