指令

什么是指令

指令,directives,是vue非常常用的功能,在template里。

  • 都是以v-开头
  • 不是自己所为html元素,比如假设指令叫v-abc,没有这种写法,这是组件(component)的写法,组件也是vue的一个强大功能
  • 都是在html元素里写,比如
    或者
    这样子的写法居多
  • 主要都是用于决定是否渲染,怎么渲染的功能

v-if指令

  • html元素根据v-if的结果是否为真从而决定是否渲染
  • 放在html元素里,比如div,也可以放在vue的<template>里(v-show不行)
  • 用等于号赋予表达式
  • 表达式需要用等号包裹
  • 表达式里直接写变量名称,变量不需要再用等号包裹,比如
    ,如果status的值为1,这个div就会渲染显示,否则不显示
  • 如果是字符串,可以加单引号,这么写:

    ...

注意,cnblogs里不能直接写template标签,要用markdown的单引号包裹起来,否则后面的内容不显示。

v-else-if和v-else指令

  • 必须和v-if指令配置使用
  • 写法为比如:
    ...

v-for指令

  • 列表的循环渲染指令
  • 必须用in来使用
  • 比如:

购物车

下面通过vue实现一个购物车的增加、减少商品数量,并且自动计算总价格的功能。

实现后的样子如下图:

html

html的代码如下。

  1. <div id="app" v-cloak>
  2. <!-- vue指令:v-if,放在标签中,如果为真则该标签会显示 -->
  3. <template v-if="list.length">
  4. <table>
  5. <thead>
  6. <tr>
  7. <th></th>
  8. <th>商品名称</th>
  9. <th>商品单价</th>
  10. <th>商品数量</th>
  11. <th>操作</th>
  12. </tr>
  13. </thead>
  14. <tbody>
  15. <!-- vue的指令:v-for -->
  16. <tr v-for="(item, index) in list">
  17. <td>{{ index + 1 }}</td><!-- vue都是用{{}}来使用变量 -->
  18. <td>{{ item.name }}</td>
  19. <td>{{ item.price }}</td>
  20. <td>
  21. <!-- vue指令:v-on,绑定事件 -->
  22. <button v-on:click="handleReduce(index)">-</button>
  23. {{ item.count }}
  24. <!-- v-on的语法糖:@,一般都是用@,不写v-on -->
  25. <button @click="handleAdd(index)">+</button>
  26. </td>
  27. <td><button @click='handleRemove'>移除</button></td>
  28. </tr>
  29. </tbody>
  30. </table>
  31. <div>总价:¥ {{ totalPrice }}</div>
  32. </t emplate>
  33. <!-- v-if放在template标签,而v-else可以放在div,也就说不需要有标签的对应关系。
  34. 但是需要有层次的对应关系,如果放在div外,则不生效。 -->
  35. <div v-else>您的购物车为空</div>
  36. </div>

js

  1. var app = new Vue({
  2. el: '#app',
  3. data: {
  4. // list是一个数组
  5. list: [
  6. // id等不需要引号
  7. { id: 1, name: 'iphone XS', price: 6599, count: 1 },
  8. { id: 2, name: 'iphone XR', price: 4399, count: 1 },
  9. { id: 3, name: 'iphone XS Max', price: 7499, count: 1 }
  10. ]
  11. },
  12. computed: {
  13. totalPrice: function () {
  14. return this.list[0].price * this.list[0].count;
  15. }
  16. },
  17. methods: {
  18. // 方法定义用:号,不能用=号
  19. handleAdd: function (index) {
  20. this.list[index].count++;
  21. },// 方法之间必须有逗号分隔
  22. handleReduce: function (index) {
  23. if (this.list[index].count > 0)
  24. this.list[index].count--;
  25. },
  26. handleRemove: function (index) {
  27. // js的spilce函数:(start: number, deleteCount?: number),vscode会提示详细解释。
  28. this.list.splice(index, 1);
  29. }
  30. }
  31. })

css

  1. table{
  2. border: 1px solid #e9e9e9;/*表格框宽度、显示、颜色*/
  3. border-collapse: collapse;
  4. border-spacing: 0;
  5. empty-cells: show;
  6. }
  7. th, td{/*表格头和表格体的样式*/
  8. padding: 8px 16px;
  9. border: 1px solid #e9e9e9;/*深灰色*/
  10. text-align: left;
  11. background: white;/*白色*/
  12. }
  13. th{/*表格头的样式*/
  14. background: #f7f7f7;/*表格头的底色:浅灰色*/
  15. color: #5c6b77;
  16. font-weight: 600;
  17. white-space: nowrap;
  18. }

2019.1.6

参考资料

《Vue.js实现》清华大学出版社