5.12

116 阅读1分钟
<body>
<!-- 插值表达式{{}},里面是JS代码,渲染的是代码对应的值 -->
<!-- v-model=''直接渲染''里对应值的内容  -->
<!-- v-html='' 渲染''里对应值里html标签里的内容 -->
<!-- v-for='' 需要循环时使用  -->
<!-- v-bind:或: 绑定属性 -->
<!-- v-on:或@ 绑定事件 -->
<div id="app">
    <table>
        <tr>
            <th>名称</th>
            <th>图片</th>
            <th>价格</th>
            <th>数量</th>
            <th>小计</th>
            <th>操作</th>
        </tr>
        
        <tr v-for="(item,i) in list">
            <td>
                <a v-bind:herf="'/detail.html?id='+item.id">{{item.name}}</a>
            </td>
            <td>
                <img :src="item.img">
            </td>
            <td>
                {{item.price.toFixed(2)}}
            </td>
            <td>
                <button :disabled="item.count===1" v-on:click="jian(item)">-</button>
                <!-- $event 当前事件对象 -->
                <input type="text" v-model="item.count" @input="checkVal($event,item)">
                <button :disabled="item.count===6" @click="item.count++">+</button>
            </td>
            <td>
                {{(item.price*item.count).toFixed(2)}}
            </td>
            <td>
                <button @click="remove(i)">删除</button>
            </td>
        </tr>
    </table>
    <h1>
        总价:{{totalPrice}}
    </h1>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    new Vue ({
        el:"#app",
        //计算属性 简化模板
        computed:{
            totalPrice(){
                let total = 0
                this.list.forEach(x=>{
                    total += x.price*x.count
                })
                return total.toFixed(2)
            }
        },
        data(){
            return {
                list:[
                    {
                        id:1,
                        name:'a',
                        img:'',//网址
                        price:100,
                        count:3
                    },
                    {
                        id:2,
                        name:'b',
                        img:'',
                        price:200,
                        count:2
                    },
                    {
                        id:3,
                        name:'c',
                        img:'',
                        price:300,
                        count:1
                    }
                ]
            }
        },
        methods:{
            remove(i){
                if (confirm("确定删除吗?"))
                    this.list.splice(i,1)
            },
            jian(item){
                item.count--
            },
            checkVal(e,item){
                let{value} = e.target
                if (!value) value = 1
                if (isNaN(value)) value = 1
                value = parseInt(value)
                if (value > 6) value = 6
                if (value < 1) value = 1
                item.count = value
            }
        }
    })
</script>
</body>