zoukankan      html  css  js  c++  java
  • vue图书小案例

    小知识点:

    vue中计算属性有缓存(对象属性变化时才会更新),方法没有缓存,所以计算属性比方法效率高
    js中let有块级作用域,var没有块级作用域,所以var是有缺陷的
    this.letters[0] = 'bb'; //vue中,这种做法并不是响应式的;推荐使用响应式方法:this.letters.splice(0,1,'cc');

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <body>
    <div id="app">
        <ul v-if="books.length">
            <ul>
                <li v-for="(v,k) in books">
                    <button @click="add(k,false)" :disabled="v.num <= 1">-</button>
                    <input type="text" :value="v.num">
                    <button @click="add(k,true)">+</button>
    
                    <div>{{v.name}}</div>
                    <div>{{v.price * v.num | showPrice}}</div>
    
                    <button @click="rm(k)">移除</button>
                </li>
            </ul>
            总价{{total_price | showPrice}}
        </ul>
    
        <div v-else>当前没有图书</div>
    </div>
    </body>
    <script>
        let v = new Vue({
            el : "#app",
            data : {
                books : [
                    {
                        name : '天龙八部',
                        price : 33,
                        num : 1,
                    },
                    {
                        name : '鹿鼎记',
                        price : 13,
                        num : 1,
                    },        
                ]
            },
            methods : {
                add : function(k,boo){
                    let obj = this.books[k];
                    if(boo) {
                        obj.num+=1;
                    }else{
                        obj.num-=1;
                    }
                    //this.books.splice(k,k+1,obj);
                },
                rm : function(k){
                    this.books.splice(k,1);
                }
            },
            // 计算属性
            computed : {
                total_price : function(){
                    let total = 0;
                    for(let i = 0;i < this.books.length;i++ ){
                        total += (this.books[i].price * this.books[i].num);
                    }
                    return total;
                }
            },
            // 过滤器
            filters : {
                showPrice : function(price){
                    return '$' + price.toFixed(2);
                }
            }
        })
    </script>
    </html>
  • 相关阅读:
    ThinkPHP5.0被攻击,发现漏洞
    ThinkPHP5.0引用PHPExcel插件,在页面中导出数据库数据
    ThinkPHP5.0引入插件
    引入UEditor插件
    Form
    点击链接只跳转到首页/本地正常,上传后,除首页外,其余页面404
    Thinkphp5中嵌套循环
    ARouter转场动画无效,试试下面这种写法
    windows下运行.sh文件
    List集合增删元素时,UnsupportedOperationException报错问题
  • 原文地址:https://www.cnblogs.com/cl94/p/12234873.html
Copyright © 2011-2022 走看看