标签: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框架。
标签:blank class bin doctype vue api接口 rom .com htm
原文地址:https://www.cnblogs.com/BigStupid/p/8821595.html