Vue - vue.js 常用指令

Vue - vue.js 常用指令

目录: 

一. vuejs模板语法之常用指令 

  1. 常用指令: v-html

  2. 常用指令: v-text

  3. 常用指令: v-for

  4. 常用指令: v-if

  5. 常用指令: v-show

  6. v-if和v-show的性能比较

  7. 常用指令: v-bind

  8. 常用指令: v-on

  9. 常用指令: v-model

  10. 常用指令: 指令修饰符

  11. 常用指令: 计算属性

  12. 常用指令: 侦听属性

  13. 常用指令: 自定义指令

  14. 常用指令: 获取DOM 元素

二.  项目: todolist 版本一 

三. 项目: todolist 版本二

 

一. vuejs模板语法之常用指令

  1. 常用指令: v-html

    可以显示htnl标签的内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    
</head>
<body>
    <div id="app">
        <div v-html="vue"></div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data: {
                    vue: '<h1>Hello Vue!</h1>>'
                }
            }
        )
    </script>
</body>
</html>

 

  2. 常用指令: v-text

    用于显示文本内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="app">
        <div v-text="name"></div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data: {
                    name: '大帅辉'
                }
            }
        )
    </script>
</body>
</html>

 

  3. 常用指令: v-for

    运用循环来渲染, 数组和对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="app">
        <div v-for="item in name">{{item}}</div>
        <div v-for="i in song">{{i.aa}}|{{i.黄家驹}}</div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data: {
                    name: [
                        "大帅辉",
                        "大帅逼",
                        "大傻逼"
                    ],
                    song:[
                        {
                        aa: "关不上的窗",
                        bb: "子时过," ,
                        黄家驹: "大地"
                    },{
                        aa: "关不上的窗",
                        bb: "子时过," ,
                        黄家驹: "大地"
                    }
                    ]
                }
            }
        )
    </script>
</body>
</html>

 

  4. 常用指令: v-if

    通过条件判断 显示标签, 底层是通过 appendChild 实现的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="app">
        <div v-if="eat == 'apple'">
            <h1>胖一斤</h1>
        </div>
        <div v-else-if="eat == 'orange'">
            <h1>胖两斤</h1>
        </div>
        <div v-else>
            <h1>一点也不胖</h1>
        </div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data:{
                    eat:"dd"
                }
            }
        )
    </script>
</body>
</html>

 

  5. 常用指令: v-show

    通过样式的display 用来控制显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="app">
        <div v-show="isShow">
            <h1>胖一斤</h1>
        </div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data:{
                    isShow: true
                }
            }
        )
    </script>
</body>
</html>

 

  6. v-if和v-show的性能比较

我们简单比较一下二者的区别:

实现方式:v-if底层采用的是appendChild来实现的,v-show通过样式的display控制标签的显示,正因为实现方式上面有差异,导致了他们的加载速度方面产生了差异;

加载性能:v-if加载速度更快,v-show加载速度慢

切换开销:v-if切换开销大,v-show切换开销小

v-if是惰性的,它是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建,v-show 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。

v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。

一般来说,v-if有更高的切换开销,而v-show有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用v-show较好,如果在运行时条件很少改变,则使用v-if较好。

 

  7. 常用指令: v-bind

    绑定属性, 注意冒号后面跟标签的属性, 属性后面的符号指向数据, 他可以简写: class: href.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .active{
            background-color: #1f23ff;
        }
    </style>
</head>
<body>
    <div id="app">
        <div>
            <a v-bind:href="link" v-bind:class="{active: isActive}">孔辉博客园</a>
        </div>
    </div>
    <script src="vue.js"></script>

    <script>
        let app = new Vue(
            {
                el : "#app",
                data:{
                    link: "https://home.cnblogs.com/u/konghui/followees/",
                    isActive: true
                }
            }
        )
    </script>
</body>
</html>

 

  8. 常用指令: v-on

    可以在标签上面绑定事件, 

     methods: 具体事件的实现方式

     click: 鼠标点击

     mouseenter: 鼠标移入

     mouseleave: 鼠标移除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .active{
            background-color: #1f23ff;
        }
    </style>
</head>
<body>
    <div id="app">
            <!--方式一: 绑定一个事件-->
            <a v-bind:href="link"
                v-bind:click="{active: isActive}"
                v-on:click="myClick">
                孔辉博客园
            </a>
            <button v-on="{click: myClick,
                            mouseenter: mouseEnter,
                            mouseleave: mouseLeave}">
                点我得到你的爱情
            </button>
    </div>
    <script src="vue.js"></script>

    <script>
        //绑定属性, 简写冒号
        let app = new Vue(
            {
                el : "#app",
                data:{
                    link: "https://home.cnblogs.com/u/konghui/followees/",
                    isActive: false
                },
                methods:{
                    // 点击的事件
                    myClick: function () {
                        console.log("爱像一阵风");
                    },
                    // 鼠标移入的事件
                    mouseEnter: function () {
                        console.log("悄悄的来");
                    },
                    // 鼠标移除的事件
                    mouseLeave: function () {
                        console.log("轻轻的走");
                    }
                }
            }
        )
    </script>
</body>
</html>

 

 

  9. 常用指令: v-model

    上面演示的是通过vue实例将数据渲染进模板,并且在控制台,我们修改数据之后,修改后的数据能够及时(官方称之为响应式)的渲染到模板层,那么,如果有这样的需求,比如有一个input标签,当用户修改渲染的原始数据后,打印修改后的数据,简单说,我们需要vue实例可以帮我们渲染数据并响应式的监听数据修改,同时我们还需要监听用户行为,如果用户在标签上面修改了数据(之前的修改,指的是通过vue实例app01进行的数据修改),我们需要获取到数据,针对这个需求,我们可以使用v-mode指令。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-model</title>
</head>
<body>
    <div id="app01">
        <p>请选择你的性别</p>
        <br>
        <input v-model="name"/>
        <p><input type="text" v-model="name"/></p>
        <p>
            <input type="checkbox" value="男" v-model="gender"/>
            <input type="checkbox" value="女" v-model="gender"/>
        </p>
        <br>
        {{ name }}
        {{ gender }}

        <p>请选择你的女朋友</p>
        <select name="" id="" v-model="girlFriends">
            <option>alex</option>
            <option>pizza</option>
            <option>peiqi</option>
        </select>
        <br>
        {{ girlFriends }}

        <p>
            <textarea v-model="article"></textarea>
        </p>
        <br>
        {{ article }}
    </div>
    <script src="./vue.js"></script>
    <script>
        let app01 = new Vue({
            el: "#app01",
            data: {
                name: "alex",
                gender: [],
                girlFriends: [],
                article: "这是一篇文章",
            }
        })
    </script>
</body>
</html> 

  

  10. 常用指令: 指令修饰符

    在指令后面加上number修饰符,限定用户输入的数据类型

    计算属性是通过过滤多个数据之后的结果,不一定是data中已存在的数据。

    v-model.number: 

    v-model.trim:

    v-model.lazy:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app01">
        <table border="1">
            <thead>
                <tr>
                    <th>学科</th>
                    <th>成绩</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Python基础</td>
                    <td><input type="text" v-model.number="python"/></td>
                </tr>
                <tr>
                    <td>前端</td>
                    <td><input type="text" v-model.lazy="web"/></td>
                </tr>
                <tr>
                    <td>Django</td>
                    <td><input type="text" v-model.trim="django"/></td>
                </tr>
            </tbody>
        </table>
    </div>

    <script>
        let app01 = new Vue({
            el: "#app01",
            data: {
                python: 75,
                web: 98,
                django: 88
            }
        })
    </script>

</body>
</html>

 

 

  11. 常用指令: 计算属性

    计算属性用来监听多个数据,每次页面加载,计算属性中的函数立即执行,但是只要原数据不被修改,那么,就不会触发重新计算,计算属性会使用计算后的缓存结果,只当原数据修改时,才会重新计算并将结果缓存起来。计算属性的计算结果可以当做data中的数据一样使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app01">
        <table border="1">
            <thead>
                <tr>
                    <th>学科</th>
                    <th>成绩</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Python基础</td>
                    <td><input type="text" v-model.number="python"/></td>
                </tr>
                <tr>
                    <td>前端</td>
                    <td><input type="text" v-model.trim="web"/></td>
                </tr>
                <tr>
                    <td>Django</td>
                    <td><input type="text" v-model.lazy="django"/></td>
                </tr>
                <tr>
                    <td>总分</td>
                    <td>{{ python + web + django }}</td>
                </tr>
                <tr>
                    <td>平均分</td>
                    <td>{{ avgScore }}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <script>
        // 计算属性放在缓存当中,只有数据修改时才重新计算
        let app01 = new Vue({
            el: "#app01",
            data: {
                python: 75,
                web: 98,
                django: 88
            },
            computed: {
                sumScore: function () {
                    return this.python + this.web + this.django;
                },
                avgScore: function () {
                    return this.sumScore/3;
                }
            }
        })
    </script>

</body>
</html>

 

 

  12. 常用指令: 侦听属性

    计算属性用来监听多个属性,我们也可以使用它来监听一个属性,但是页面加载即执行计算并不符合我们的需求,如何只在数据被修改后出发相应事件,vue提供给我们的是watch,即侦听属性。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>
<body>
  <div id="app">
    <p>Original message: {{ message }}</p>
    <p>Computed message: {{ reversedMessage }}</p>
    <p>Full name: {{ fullName }}</p>
    <p><input type="text" v-model="firstName"/></p>
    <p><input type="text" v-model="lastName"/></p>
  </div>

  <script>
    new Vue({
      el: "#app",
      data: {
        message: "Hello Vue!",
        firstName: "Foo",
        lastName: "Bar",
        fullName: "Foo Bar",
      },
      computed: {
        reversedMessage: {
          get: function () {
            console.log(1);
            // 多次刷新reversedMessage不会改变, 除非message发生改变
            return this.message.split('').reverse().join('');
          }
        }
      },
      watch: {
        firstName: function (value) {
          console.log(value);
          this.fullName = value + ' ' + this.lastName
        },
        lastName: function (value) {
          console.log(value);
          this.fullName = this.firstName + ' ' + value
        }
      }
    })
  </script>
</body>
</html>

 

 

  13. 常用指令: 自定义指令

    遇到一些复杂的需求,vue提供的指令不能完美的处理,有时候我们需要自定义指令,针对这一需求,vue提供了自定义指令,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义属性</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            border: 1px;
            background-color: #ff0000;
        }
    </style>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app01" class="box" v-pos.left.bottom="post">

    </div>

    <script>
        Vue.directive("pos", function (el, bindding) {
            let decorators = bindding.modifiers;
            if (bindding.value) {
                el.style['position'] = 'fixed';
                for (let key in decorators) {
                    el.style[key] = 0;
                }
            } else {
                el.style.position = "static";
            }
        });
        // 自定义属性
        let app01 = new Vue({
            el: "#app01",
            data: {
                post: true
            }
        })
    </script>

</body>
</html>

  el是我们自定义指令所在的DOM元素;

  bindding是自定义指令的一些具体数据,请记住,最重要的一点是,不管是现在还是将来,任何情况下,我们都需要根据数据进行业务处理,所以,此处最关键的也是数 据,即bindding.value。

 

  14. 常用指令: 获取DOM 元素

    某些情况下,我们需要直接获取DOM元素,并对元素进行一些加工处理。vue提供给我们$refs来获取DOM元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取DOM</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app01">
        <div ref="myBox">alex</div>
        <button v-on:click="myAlex">点击alex变红</button>
    </div>


    <script>
        // 错误实例button放在div外面
        let app01 = new Vue({
            el: "#app01",
            methods: {
                myAlex: function () {
                    this.$refs.myBox.style.color = "red";
                }
            }
        })
    </script>
</body>
</html>

 

  在DOM元素上面绑定了ref之后,vue根实例上面就会出现$refs变量,它是一个object类型,key为ref后面的自定义名称,而value为DOM元素。我们通过this.$refs拿到object,之后就可以通过自定义的key名,来找到DOM元素

 

二.  项目实例

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #practice {
        margin: 0 auto;
        left: 0;
        right: 0;
    }

    .left {
        float: left;
        width: 50%;
    }

    .right {
        float: right;
        width: 50%;
    }
</style>
<script src="vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<body>
<div id="practice">
    <el_card class="box-card">
        <div slot="header">
            <span>TodoList</span>
            <input id="waitInput" v-model="waitInput" v-on:click="todoEnter">
            <button v-on:click="todoEnter">
                添加待办
            </button>
        </div>

        <div class="left">
            <div>待办</div>
            <div v-for="(todo, index) in todoThings" key="index">
               <button v-on:click="backButton(index)"></button>
                {{todo}}
                <!--<button>添加到已办</button>-->
            </div>
        </div>

        <div class="right">
            <div>已办</div>
            <div v-for="(done, index) in doneThings" key="index">
                <button v-on:click="doneButton(index)"></button>
                {{done}}
                <!--<button>添加到已办</button>-->
            </div>
        </div>
    </el_card>


</div>


<script>
    new Vue({
        el: "#practice",
        data: {
            waitInput: "",
            currentThing: "",
            checked: true,
            todoThings: ['写代码', '五道口吃火锅', '超市买鸡蛋', '图书馆看书', '看电影', '看演唱会', '游泳', '跑步'],
            doneThings: ['看书', '写博客', '散步', '与朋友聊天', '打电话给父母']
        },
        methods: {
            todoEnter: function () {
                if (this.waitInput){
                    this.todoThings.push(this.waitInput);
                    // this.waitInput = "";
                }
            },
            backButton:function (index) {
                event.currentTarget.checked = false;
                things = this.todoThings.splice(index, 1)[0];
                this.doneThings.push(things);
            },
            doneButton:function (index) {
                event.currentTarget.checked = false;
                things = this.doneThings.splice(index, 1)[0];
                this.todoThings.push(things);
            }
        },
    })
</script>
</body>
</html>
项目 - todolist - 简易版
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>使用Vue实现todoList</title>
  <!--<script src="../statics/vue.min.js"></script>-->
    <script src="VUE/vue.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .container {
      width: 500px;
      height: auto;
      margin: 0 auto;
    }
    .container .header {
      text-align: center
    }
    li {
      list-style-type: none
    }
    div.left {
      float: left;
      margin-left: 50px;
    }
    div.right {
      float: right;
      margin-right: 50px;
    }
    li {
      margin-top: 5px;
    }
  </style>
</head>
<body>

  <div id="app">
    <div class="container">
      <!--头部添加待办-->
      <div class="header">
        <input id="addthings" @keyup.enter="todoEnter" v-model="todo">
        <span @click="todoEnter">添加待办</span>
      </div>

      <!--已办和待办最外层的盒子-->
      <div class="box">
        <!--已办事项-->
        <div class="left">
          <span>待办事项</span>
          <div class="todos">
            <ul>
              <li v-for="(todo, index) in todoThings" :key="index">
                <input type="radio" name="todo" v-on:click="addThing(index)"><span>{{ todo }}</span>
              </li>
            </ul>
          </div>
        </div>

        <!--待办事项-->
        <div class="right">
          <span>已办事项</span>
          <div class="dones">
            <ul>
              <li v-for="(done, index) in doneThings" :key="index">
                  <input type="radio" name="done" v-on:click="delThing(index)"><span>{{ done }}</span>
              </li>
            </ul>
          </div>
        </div>

      </div>

    </div>

  </div>
  <script>
    new Vue({
      el: "#app",
      data: {
        todo: '',
        addDone: '',
        todoThings: ['写代码', '五道口吃火锅', '超市买鸡蛋', '图书馆看书', '看电影', '看演唱会', '游泳', '跑步'],
        doneThings: ['看书', '写博客', '散步', '跟朋友聊天', '打电话给父母', '学炒菜', '洗衣服', '打扫房间']
      },
      methods: {
        todoEnter: function () {
          if (this.todo) {
            this.todoThings.push(this.todo);
            this.todo = '';
          }
        },
        addThing: function (index) {
          event.currentTarget.checked = false;
          things = this.todoThings.splice(index, 1)[0];
          this.doneThings.push(things);
        },
        delThing: function (index) {
          event.currentTarget.checked = false;
          things = this.doneThings.splice(index, 1)[0];
          this.todoThings.push(things);
        }
      }
    })
  </script>
</body>
</html>
项目 - todolist - 升级版
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .im {
            width: 80px;
            height: 50px;
            /*background-color: #6b49ff;*/
        }
    </style>
    <script src="vue.js"></script>
</head>
<body>
<div id="app">
    <div class="im">
        <img :src="imageArray[currentIndex].imgSrc" alt=""
        style="width:150px;height: 150px"
        v-on="{ mouseenter: mouseEnter, mouseleave:mouseLeave}"
        >
        <button v-on:click="prevImage">上一页</button>
        <button v-on:click="nextImage">下一页</button>
    </div>

</div>

<script>
    new Vue({
        el: "#app",
        data: {
            imageArray: [
                {id: 1, imgSrc: "../imgege/1.jpg"},
                {id: 2, imgSrc: "../imgege/2.jpg"},
                {id: 3, imgSrc: "../imgege/3.jpg"},
                {id: 4, imgSrc: "../imgege/4.jpg"},
            ],
            currentIndex: 0,
        },
            methods: {
            prevImage:function () {
                this.currentIndex = this.currentIndex -1;
                if (this.currentIndex < 0 ){
                    this.currentIndex= this.imageArray.length - 1;
                }
            },
            nextImage:function () {
                this.currentIndex = this.currentIndex + 1;
                if (this.currentIndex === this.imageArray.length){
                    this.currentIndex= 0;
                }
            },
            mouseEnter:function () {
            clearInterval(this.interval);
        },
            mouseLeave:function () {
            this.interVal = setInterval(() =>{
                this.currentIndex = this.currentIndex + 1;
                if (this.currentIndex === this.imageArray.length){
                    this.currentIndex = 0;
                }
            }, 1000)
        },
        },

            created(){
                this.interval = setInterval(() =>{
                    this.currentIndex = this.currentIndex + 1;
                    if (this.currentIndex === this.imageArray.length){
                        this.currentIndex = 0;
                    }

                },1000)
        }
    })
</script>
</body>
</html>
项目 - 轮播图
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="vue.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .active {
            background-color: #6cff44;
        }
    </style>

</head>
<body>
<div id="app">
    <audio :src="musicAry[currentIndex].musicSic"
           autoplay="autoplay" controls="controls"></audio>
    <ul>
        <li v-for="(music, index) in musicAry " :key="index"
            @click="playCurrentSong(index)"
            :class="{ active: currentIndex===index}">
            <h2>歌曲:{{music.name}}</h2>
            <h3>歌手:{{music.author}}</h3>
        </li>
    </ul>

</div>

<script>
    new Vue({
        el: "#app",
        data: {
            musicAry: [
                {id: 1, author: "张国荣", musicSrc: "", name: "春夏秋冬"},
                {id: 2, author: "谭咏麟", musicSrc: "", name: "弹脑壳"},
                {id: 3, author: "Beyang", musicSrc: "", name: "海阔天空"},
                {id: 4, author: "周传熊", musicSrc: "", name: "关不上的窗"},
            ],
            currentIndex: 0,
            active: '',
        },
        methods: {
            playCurrentSong: function (index) {
                this.currentIndex = index;
                this.active = 'active';
            }
        },
    })
</script>
</body>
</html>
音乐播放器

 

 

猜你喜欢

转载自www.cnblogs.com/konghui/p/10196925.html