博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2018-04-13 16:43  哈哈丶大傻瓜  阅读(786)  评论(0编辑  收藏  举报
<!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全攻略