Vue学习(一) :入门案例

开始前的准备

IDE:VSCode(推荐)或者Sublime Text
前导技术:JavaScript中级

案例

页面代码:

<div id="app">
    <ul>
        <li v-for="product in products">
            <input type="number" v-model.number="product.quantity">
              {{ product.name }} <!--using double { to define an expression-->
            <span v-if="product.quantity === 0">
                - OUT OF STOCK
            </span>
            <span v-if="product.quantity < 0 || product.quantity % 1 != 0">
                - INVALID NUMBER
            </span>
            <button @click="product.quantity += 1">
              Add
            </button>
            <button @click="product.quantity -= 1">
              Minus
            </button>
        </li>
    </ul>
    <h2>Total Inventory: {{ totalProducts }}</h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    const app = new Vue({
        el: '#app', 
        data: {
            products: []
        },
        computed: {
            totalProducts () { // Here totalProducts() is a property of computed
                return this.products.reduce((sum, product) => {
                    return sum + product.quantity
                }, 0)
            }
        },
        created () {
            fetch('https://api.myjson.com/bins/clqnb')
              .then(response => response.json())
              .then(json => {
                  this.products = json.products
              })
        }
    })
</script>

json测试数据:

{
    "products":[
        {"id":1,"quantity":1,"name":"Compass"},
        {"id":0,"quantity":2,"name":"Jacket"},
        {"id":3,"quantity":5,"name":"Hiking Socks"},
        {"id":4,"quantity":2,"name":"Suntan Lotion"}
    ]
}

json托管(提供API):http://myjson.com/

注意:此处需能够访问的代理服务器!

猜你喜欢

转载自www.cnblogs.com/xsjzhao/p/11006917.html
今日推荐