Vue初识

▼魔方 西西 提交于 2020-03-22 11:11:54

1、Vue.js 是什么

Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

2、引入Vue.js

初学,所以直通过CDN服务器引入vue库

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue1</title>
<!-- 通过CDN服务器引入vue库 -->
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

3、vue在js中语法

    <script>
        var vm  = new Vue({
            el : "#app",
            data : {
                msg : "hello world!!!",
                age : 30,
                lastName:"wang",
                firstName : "zhenling",
                fullName : "zhenling wang"
            },
            //方法
            methods : {
                getFullName : function(){
                    return this.firstName + " " + this.lastName
                    // 必须用this,这里this指vm这个实例
                }
            }
        })
    </script>

注意: Vue本身是一个构造函数,new Vue实例化,el指element,通过css选择器选出id为app的元素,data定义内容。最后用{{ msg }}的语法在div里调用,methods定义方法

4、vue在html中的语法一:双括号

其中:双花括号里可以写属性名、简单表达式、函数即方法
①属性名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue1</title>
    <!-- 通过CDN服务器引入vue库 -->
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
       {{ msg }} 
    </div>
   <script>
        new Vue({
            el : "#app",
            data : {
                msg : "hello world!!!",
            }
        })
    </script>
</body>
</html>

②简单表达式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue1</title>
    <!-- 通过CDN服务器引入vue库 -->
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
            <!-- 例如:三目运算符 -->
        {{ age > 60 ? "老人" : "青年"}}</br>
            <!-- 例如:普通表达式 -->
        {{firstName + " " + lastName}}</br>
    </div>
    <script>
        var vm  = new Vue({
            el : "#app",
            data : {
                msg : "hello world!!!",
                age : 30,
                lastName:"wang",
                firstName : "zhenling"
            }
    </script>
</body>
</html>

③函数(即方法)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue1</title>
    <!-- 通过CDN服务器引入vue库 -->
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        {{ fullName}}</br>
            <!-- 例如分别取姓和名,结果[ "zhenling", "wang" ] -->
        {{fullName.split(" ")}}</br>
            <!-- 例如只取名,结果zhenling-->
        {{fullName.split(" ")[0]}}</br>
            <!-- 例如只取姓,结果wang-->
        {{fullName.split(" ")[1]}}</br>
            <!-- 例如:函数执行,不带参数-->
        {{ getFullName()}}</br>
            <!-- 例如:函数执行,带参数-->
        {{ getFullName(firstName,lastName)}}
    </div>
    <script>
        var vm  = new Vue({
            el : "#app",
            data : {
                msg : "hello world!!!",
                age : 30,
                lastName:"wang",
                firstName : "zhenling",
                fullName : "zhenling wang"
            },
           //不带参数写法
            methods : {
                getFullName : function(){
                    return this.firstName + " " + this.lastName
                    // 必须用this,这里this指vm这个实例
                }
            }
            //带参数写法
            // methods : {
            //     getFullName : function(first,last){
            //         return first + " " + last
            //     }
            // }

        })
    </script>
</body>
</html>

5、Vue在html中的语法二:指令

5.1 v-bind指令

vue指令语法: v-指令名字 + :+ 指令的参数 = 指令的表达式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <!-- 此处用vue的指令v-bind,绑定href这个属性 -->
        <a v-bind:href="url">百度一下</a>
    </div>
    <script>
        //vue指令语法: v-指令名字 + :+ 指令的参数 = 指令的表达式
        new Vue({
            el : "#app",
            data : {
                url : "http://www.baidu.com"
            }
        })
    </script>
</body>
</html>

 相关练习:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>练习</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    
</head>
<body>
    <div id="app">
        <!-- 输出一个电影的名字和上映日期 -->
        电影名:{{movieTitle}}
        上映日期:{{movieDate}}
        <!-- 判断一部电影是否是新电影,>2000年新,否则老电影 -->
        这部电影是 {{getMovie()}} 电影
        <!-- title的绑定 -->
        <div v-bind:title = "movieTitle">
            hover me!!!!
        </div>
    </div> 
    <script>
    new Vue({
        el : "#app",
        data :{
            movieTitle :"妖猫传",
            movieDate : "1999"
        },
        methods :{
            getMovie :function(){
                return this.movieDate > 2000 ? "新" : "旧" 
            }
        }
    })
    </script>
</body>
</html>

5.2 v-on指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
            <!-- 普通写法 -->
        <!-- <button v-on:click = "showsome">click me!!!</button> -->
            <!-- 默认事件 -->
        <!-- <button v-on:click = "showsome($event)">click me!!!</button> -->
            <!-- 传参写法 -->
        <!-- <button v-on:click = "showsome(123123,$event)">click me!!!</button> -->
    </div>
    <script>
        new Vue({
            el : "#app",
            // 普通写法
            // methods : {
            //     showsome :function(){
            //         alert("show something")
            //     }
            // }
            // 默认事件
            // methods : {
            //     showsome :function(event){
            //         console.log(event)
            //         alert("show something")
            //     }
            // }
            // 传参写法
            methods : {
                showsome :function(msg,event){
                    console.log(msg)
                    alert("show something")
                }
            }
        })
    </script>
</body>
</html>

5.3 修饰符-阻止冒泡.stop

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
             <!-- 阻止冒泡,用事件修饰符.stop -->
        <div v-on:click = "showsome(1,$event)">
            <button v-on:click.stop = "showsome(123123,$event)">click me!!!</button>
        </div>
    </div>
    <script>
        new Vue({
            el : "#app",
            methods : {
                showsome :function(msg,event){
                    console.log(msg)
                    alert("show something")
                }
            }
        })
    </script>
</body>
</html>

5.4 修饰符-阻止默认事件.prevent

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
            <!-- 阻止默认事件 下例阻止a标签点击跳转的默认事件-->
        <a href="http://www.baidu.com" v-on:click.prevent>link me!!</a>
        <a href="http://www.baidu.com" v-on:click.prevent="showsome">link me!!</a>
    </div>
    <script>
        new Vue({
            el : "#app",
            methods : {
                showsome :function(msg,event){
                    console.log(msg)
                    alert("show something")
                }
            }
        })
    </script>
</body>
</html>

5.5 v-on指令的按键修饰符

按键修饰符 .enter .space .esc .13(代表enter键)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
       <input type="text" v-on:keyup.enter = "keyup">
       <!-- 按enter时弹出框 -->
       <input type="text" v-on:keyup.enter.space = "keyup">
       <!-- 按enter或者space时弹出框 -->
    </div>
    <script>
        new Vue({
            el : "#app",
            methods :{
                keyup :function(event){
                    // if(event.which == 13){
                    //     // 回车键的which属性是13
                        alert("you pressed enter!!");
                    // }用按键修饰符,解放以上代码
                }
            }
        })
    </script>
</body>
</html>

5.6 v-on指令的系统修饰符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
       <!-- 系统修饰符shift,和shift同时按下才能触发 -->
       <input type="text" v-on:keyup.shift = "keyup">
       <button type="text" v-on:click.shift = "keyup">click</button>
       <!-- 系统修饰符meta,和window或mac键同时按下才能触发 -->
       <button type="text" v-on:click.meta = "keyup">click</button>
    </div>
    <script>
        new Vue({
            el : "#app",
            methods :{
                keyup :function(event){
                        alert("you pressed enter!!");
                }
            }
        })
    </script>
</body>
</html>

5.7 相关练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>练习</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    
</head>
<body>
    <div id="app">
            <!--通过输入框内容改变输出内容 -->            
        <input type="text" v-on:keyup = "changeName">
        output : {{name}}
             <!--通过输入框内容改变输出内容,必须同时按住shift键-->
             <!-- 以下两种写法 -->
        <input type="text" v-on:keyup.shift = "name = $event.target.value"> <!-- 此处必须用$event -->
        output : {{name}}
        <input type="text" v-on:keyup.shift = "changeName">
        output : {{name}}

            <!--阻止action提交内容默认事件-->
        <form action="" v-on:submit.prevent>
            <input type="submit">
        </form>
    </div> 
    <script>
        new Vue({
            el : "#app",
            data :{
                name : "hello"
            },
            methods :{
                changeName:function(event){
                    this.name = event.target.value
                }
            }
        })
    </script>
</body>
</html>

5.8 双向数据绑定v-model

复杂写法:v-on+v-bind

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        {{ value }}
        <input type="text" v-bind:value = "value" v-on:input = "input">
            <!-- 此处v-bind将js和html里面的数据绑定,js改变html里面的数据 -->
            <!-- 此处v-on将html和js里面的数据绑定,改变html的dom节点的数据,就会改变js里面的数据 -->
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                value: "wangzhenling",
            },
            methods:{
                input : function(event){
                    this.value = event.target.value
                }
            }
        })
    </script>
</body>
</html>

简单写法:v-model

注意:双向数据绑定简单写法 v-model:实现两步v-bind和v-on

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        {{ name }}
        <input type="text" v-model = "name">
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                name:"wangzhenling"
            }
    </script>
</body>

</html>

5.9 v-model修饰符

①.trim

.trim 去掉首尾空格修饰符
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        {{ name }}
        <input type="text" v-model.trim = "name">  
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                name: "wangzhenling"
            }
    </script>
</body>
</html>

②.number

.number转换成数字类型修饰符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        {{ name }}
        <input type="text" v-model.number = "name">  
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                name: "wangzhenling"
            }
    </script>
</body>
</html>

③.lazy

.lazy修饰符   input失去焦点才会把input里的值绑定给name
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        {{ name }}
        <input type="text" v-model.lazy = "name">  
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                name: "wangzhenling"
            }
    </script>
</body>
</html>

5.10 v-html指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 下面语法输出内容为<h1>hello</h1>-->
        {{ html }}
        <!-- v-html指令 输出内容为 hello-->
        <div v-html = "html"></div>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                html :"<h1>hello</h1>",
                message : "wangzhenling"
            }
        })
    </script>
</body>

</html>

5.11 v-once指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <div v-once>
            <!--有v-once指令,只渲染一次,希望数据有一个初始化值,不希望随着message改变而改变 -->
            {{ message }}
        </div>
            <!-- 此时没有v-once指令,当点击,message值变成123 -->
        {{ message }}
        <button v-on:click = "message = '123'">click me!!</button>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                html :"<h1>hello</h1>",
                message : "wangzhenling"
            }
        })
    </script>
</body>

</html>

5.12 v-if指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <p v-if = "items > 10">{{ items }} 个,有现货</p>
        <p v-else-if = "items > 1">所剩不多了,快点买吧</p>
        <p v-else>没有库存了,请耐心等待</p>

        <!-- 同一个条件判断多个语句用templete包裹,且template不会被渲染 ,是html5标签 -->
        <template v-if = "items > 50">
            <p>注意事项</p>
            <p>因为还有很多,现在购买打8折</p>
        </template>
    </div>
    <script>
        new Vue({
            el: "#app",
            data :{
                items : 52,
            }
        })
    </script>
</body>

</html>

5.13 v-show指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <P v-show = "skill">我发射了技能</P>
        <P v-show = "!skill">我不能发射技能</P>
        <button v-on:click = "skill = !skill">发射技能</button>
    </div>
    <script>
        new Vue({
            el: "#app",
            data :{
                items : 52,
                skill : true
                // 或者 skill : false
            }
        })
    </script>
</body>

</html>

5.14 v-cloak指令

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        /* 当vue库还没加载出来,不显示元素,当vue显示出来,v-cloak会自动消失,以下代码也就不会生效 */
        [v-cloak]{
            display: none;
        }
    </style>
</head>

<body>
    <div id="app">
        <!-- 加入网速很慢,html渲染完,vue.js还没加载完,就会显示不完全,此时需要用v-cloak ,全部加载完,v-cloak消失-->
        <div v-cloak>
            {{ message }}
        </div>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
        setInterval(function () {
            new Vue({
                el: "#app",
                data: {
                    message: "wangzhenling"
                }
            })
        }, 3000)
        // 借助定时器来看v-cloak的效果
    </script>
</body>
</html>

5.15 v-for指令在数组中应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <h1>电影列表</h1>
        <ul>
            <!-- 数组 -->
            <!-- v-for语法:别名 in 表达式 -->
            <li v-for = "title in movies"> {{ title }}</li>
            <!-- 带索引 -->
            <li v-for = "(title , index) in movies"> {{ title }}({{ index }})</li>
            <!-- 下面写法也可以 -->
            <li v-for = "(t , i) in movies"> {{ t }}({{ i }})</li>
        </ul>
    </div>
    <script>
        new Vue({
            el : "#app",
            data :{
                // 数组
                movies : ["妖猫传","芳华","至暗时刻"],
            }
        })
    </script>
</body>
</html>

5.16 v-for指令在对象中应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
          <!-- 对象 -->
          <table>
              <thead>
                <td>姓名</td>
                <td>教授课程</td>
                <td>水平</td>
                <td>公司</td>                       
              </thead>
              <tbody>
                <tr v-for = "person in persons">
                    <td>{{ person.name }}</td>
                    <td>{{ person.title }}</td>
                    <td>{{ person.level }}</td>
                    <td>{{ company }}</td>
                </tr>
              </tbody>
          </table>
           <!-- 对象,带有索引 -->
           <table>
                <thead>
                  <td>姓名</td>
                  <td>教授课程</td>
                  <td>水平</td>
                  <td>索引</td>           
                </thead>
                <tbody>
                  <tr v-for = "(person,index) in persons">
                      <td>{{ person.name }}</td>
                      <td>{{ person.title }}</td>
                      <td>{{ person.level }}</td>
                      <td>{{ index }}</td>
                  </tr>
                </tbody>
            </table>
    </div>
    <script>
        new Vue({
            el : "#app",
            data :{
                // 对象
                persons :[{
                    name : "liu",
                    title:"vue",
                    level:3
                },
                {
                    name:"cheng",
                    title:"javascript",
                    level:4
                    
                },
                {
                    name:"wang",
                    title:"both",
                    level:10            
                }],
                company:"duyi",
            }
        })
    </script>
</body>
</html>

5.17 v-for指令遍历对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
            <!-- v-for特殊用法 遍历对象的属性值-->
            <div v-for = "name in person">
                {{ name }}
            </div>
             <!-- v-for特殊用法 遍历对象的属性值和属性名-->
            <div v-for = "(name,prop) in person">
                    {{ prop }}:{{ name }}
                </div>
                 <!-- v-for特殊用法 遍历对象的属性值和名,带有索引-->
            <div v-for = "(name,prop,index) in person">
                    {{ prop }}:{{ name }}({{ index }})
            </div>
    </div>
    <script>
        new Vue({
            el : "#app",
            data :{
                person:{
                    lastname:"wang",
                    fastname:"zhenling",
                    age:10
                }
            }
        })
    </script>
</body>
</html>

5.18 v-for指令遍历数字

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
            <!-- 其他用法:遍历数字 -->
            <div v-for = "n in 50">
                {{ n }}
            </div>
            <!-- 遍历数字,带索引 -->
            <div v-for = "(n,index) in 50">
                {{ n }}|{{ index  }}
            </div>
    </div>
    <script>
        new Vue({
            el : "#app"
        })
    </script>
</body>
</html>

5.19 v-for指令遍历字符串

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
            <!-- 其他用法:遍历字符串 -->
            <div v-for = "s in 'wangzhenling'">
                {{ s }}
            </div>
            <!-- 其他用法:遍历字符串,带索引 -->
            <div v-for = "(s,index) in 'wangzhenling'">
                {{ s }}|{{ index  }}
            </div> 
    </div>
    <script>
        new Vue({
            el : "#app"
        })
    </script>
</body>
</html>

5.20 v-for指令注意事项

①vue.set

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
        <ul>
            <li v-for = "n in numbers">{{ n }}</li>
            <button v-on:click= "changeNumber">click me!!</button>
        </ul>
    </div>
    <script>
        new Vue({
            el : "#app",
            data : {
                numbers:[1,2,3,4,5]
            },
            methods :{
                changeNumber:function(){
                    // this.numbers[1] = 10;
                    // 这种做法不会重新渲染dom节点,因为索引不变,内存地址不会变,原数组不变,是一个js的缺陷
                    // 下述写法可以重新渲染dom节点,加上索引值,改变了地址,用Vue.set
                    Vue.set(this.numbers,1,10)
                    alert(this.numbers[1]);
                }
            }
        })
    </script>
</body>
</html>

①push,pop,shift,unshift,reverse,sort,splice,vue进行了重写,可以渲染dom

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
        <div v-for = "item in persons" v-bind:key = "item.id">
            {{ item.name }} {{ item.id }}<input type="text">需
            <!-- 加上input框,想要input框和前面的内容一起变化,要绑定一个key值,绑定一个独一无二的值,说明是一一对应的-->
        </div>
        <button v-on:click = "add">click me!!</button>
        <button v-on:click ="reverse" >reverse</button>
    </div>
    <script>
        new Vue({
            el : "#app",
            data : {
                persons:[{
                    id : 1,
                    name : "wang"
                },{
                    id : 2,
                    name : "zhen"
                },{
                    id : 3,
                    name : "ling"
                }]
            },
            methods :{
                add : function(){
                    // 此时push可以渲染dom,是因为vue底层重写了push方法,模板复用,但是有bug,加上一个input框,input里面的内容不会跟着其他内容一起改变,此时需要要绑定一个key值,
                    // 重写的方法还包括:push,pop,reverse,sort,shif,unshift,splice
                    this.persons.push({
                        id:4,
                        name: "123"
                    })
                },
                reverse:function(){
                    this.persons.reverse()
                }
            }
        })
    </script>
</body>
</html>

5.21 相关练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
        <!-- 双向数据绑定 -->
        <input type="password" v-model = "passward">

        <!-- v-if应用 -->
        <p v-if = "chars > 8">你的字符大于8个</p>
        <p v-else-if = "chars > 0">你有{{ chars }}个字符</p>
        <p v-else>你没有字符</p>

        <!-- 列表循环 -->
        <ol>
            <li v-for = "sub in subs">
                {{ sub.name }}
                <ul>
                    <li v-for = "item in sub.sub">
                        {{ item }}
                    </li>
                </ul>
            </li>
        </ol>
    </div>
    <script>
        new Vue({
            el : "#app",
            data : {
              password:"",
              chars :7,
              subs :[{
                  name : "javascript",sub:["vue","react","angular"]
              },{
                  name : "database",sub :["mysql","mongodb","sqlsever"]
              },
              {
                  name:"system",sub:["macOS","linux","windows"]
              }]
            }
        })
    </script>
</body>
</html>

6 vue属性

6.1 el属性

6.2 data属性

6.3 methods属性

6.4 计算属性 computed

计算属性computed两个特点:

①vue会检测里面的代码,只要检测到计算属性依赖的数据发生变化时,才会执行代码,下例依赖lastName或者firstName,其中一个变化,都会执行代码

②计算属性执行一次后,会有缓存,再次执行计算属性,直接走缓存,不执行代码

③conputed是一个同步的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
        <div>{{ num }}</div>
        <!-- getFullName()改成fullName,当成属性,不当成方法-->
        <div>{{ fullName }}</div>
        <div>{{ fullName }}</div>        
        <button v-on:click = "num++">add</button>
        <button v-on:click = "changeName">改变名字</button>
    </div>
    <script>
        new Vue({
            el : "#app",
            data: {
                num:0,
                firstName : "zhenling",
                lastName : "wang"
            },
            // 此时点击add,会执行console.log("我执行了"),但是没有改变lastname和firstname值,所以不需要执行,所以用computed计算属性, 代替methods
            // methods :{
            //     getFullName : function(){
            //         return this.lastName + this.firstName
            //     }
            // }
            computed :{
                // getFullName变成fullName,当成属性,不当成方法
               fullName : function(){
                    alert("我执行了");
                    return this.lastName + this.firstName;
                }
            },
            // 验证,当改变fullname值时,执行console.log
            methods : {
                changeName : function(){
                    this.lastName = "ming"
                    // this.firstName = "xiao"
                }
            }
        })
    </script>
</body>
</html>

6.5 计算属性 get 、set属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
        <div>{{ num }}</div>
        <div>{{ fullName }}</div>
        <button v-on:click = "num++">add</button>
        <button v-on:click = "changeName">改变名字</button>
        <button v-on:click = "changeFullName">改变fullname值</button>
    </div>
    <script>
        new Vue({
            el : "#app",
            data: {
                num:0,
                firstName : "zhenling",
                lastName : "wang"
            },
            // get,set属性,当获取fullname值时,走get函数,当设置fullname值时,走set函数
            computed :{
               fullName :{
                   get:function(){
                    // 如果想让fullName依赖其他数据的时候,就把操作代码写进get里
                       alert("我执行了get");
                       return this.lastName + this.firstName;
                   },
                   set:function(newName){
                    // 如果想让fullName发生改变,从而引发其他数据发生改变,就把操作代码写进set里
                       var arr = newName.split(" ");
                       this.lastName = arr[0];
                       this.firstName = arr[1];
                   }
               }
            },
            methods : {
                changeName : function(){
                    this.lastName = "ming"
                },
                changeFullName :function(){
                    this.fullName = "xiao hong"
                }
            }
        })
    </script>
</body>
</html>

6.6 计算属性 watch属性

computed和watch都是监听数据变化用,根据实际情况决定用哪个

watch两个特点:

①没有return的返回值

②可以是异步操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>    
</head>
<body>
    <div id="app">
       <input type="text" v-model = "searchInfo">
       <div v-if = "shoeSearching">正在搜索</div>
       <ul>
           <li v-for = "item in result">{{ item }}</li>
       </ul>
    </div>
    <script>
        new Vue({
            el : "#app",
            data: {
                searchInfo :"",
                shoeSearching :false,
                result : []
            },
            // watch监听数据变化,监听searchInfo
            watch:{
                searchInfo :function(query){
                    this.shoeSearching = true;
                    var vm = this;
                    // 模拟监听
                    setTimeout(function(){
                        vm.result = ["js","css","html"]
                        vm.shoeSearching = false;
                    },500)
                }
            }
        })
    </script>
</body>
</html>

6.7 相关练习

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 1、将电影写入ul li 格式:捉妖记2 (2018)-->
        <ul>
            <li v-for = "movie in formateMovie">{{ movie }}</li>
        </ul>
        <!-- 2、添加电影 -->
        <button v-on:click = "addMovie">添加电影</button>
        <!-- 3、当添加电影时,watch监测到,会弹出框提示,添加了什么电影 -->
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                movies: [{
                    name: "捉妖记2",
                    year: 2018
                },
                {
                    name: "星球大战8",
                    year: 2018
                },
                {
                    name: "谭仁杰探案",
                    year: 2018
                }]
            },
            methods :{
                addMovie :function(){
                    this.movies.push({
                        name:"祖宗十九代",
                        year :2018
                    })
                }
            },
             // movies变化,watch会监测到,然后执行watch里面的代码
            watch :{
                movies : function(newValue){
                    alert("我添加了" + newValue[newValue.length - 1].name);
                }
            },
            // movies变化,computed会监测到,然后formateMovie也会执行,改变数组格式
            computed: {
                // 改变数组格式 这里的map()是一种遍历方法
                formateMovie :function(){
                   return this.movies.map(function(movie){
                        return movie.name + " (" + movie.year + ")"
                    })
                }
            }
        })
    </script>
</body>

</html>

7 filter过滤器(筛选)及样式转换

7.1 filter过滤器

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 简单应用 ,转换成大写-->
       <!-- {{ msg | upperCase}} -->
       <!-- 复杂应用 ,首字母大写,true指第二个参数存在-->
       {{ msg | upperCase(true) }}       

    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
               msg :"hello world!!"
            },
            // uppercase简单应用
            // filters:{
            //     upperCase : function(val){
            //         return val.toString().toUpperCase();
            //     }
            // } 

            // uppercase复杂应用
            filters :{
                upperCase : function(val,isFirstLetter){
                    val = val.toString();
                    if(isFirstLetter){
                        return val.charAt(0).toUpperCase() + val.slice(1);
                    }else{
                        return val.toUpperCase();
                    }
                }
            }
        })
    </script>
</body>

</html>

7.2 相关练习

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
       <!-- 1、写出Hello World-->
       <div v-bind:title="msg|firstLetterUp">{{ msg|firstLetterUp }}</div>

       <!-- 2、不要空格-->
       <div v-bind:title="msg|firstLetterUp|removeSpace">{{ msg|firstLetterUp|removeSpace }}</div>
       <!-- 3、改变顺序 -->
       <div v-bind:title="msg|removeSpace|firstLetterUp">{{ msg|removeSpace|firstLetterUp }}</div>   
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
               msg :"hello world!!"
            },
            filters :{
                // 1、写出Hello World
                firstLetterUp :function(val){
                    val = val.toString();
                    var arr = val.split(" ");
                    var newarr = arr.map(function(value){
                        return value.charAt(0).toUpperCase() + value.slice(1);
                    })
                    return newarr.join(" ");
                },
                // 1、去掉空格
                removeSpace :function(val){
                    return val.toString().replace(/ /g,'');
                }
            }
        })
    </script>
</body>

</html>

8 样式变换 style

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>

<body>
    <div id="app">
       <div style="width:200px;" v-bind:style = "[styles1,styles2,{height:'200px'}]"></div>
       <button v-on:click = "change">change</button>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
               color:"yellow",
               styles :{
                   backgroundColor : this.color
               },
               styles2:{
                   'border-radius':"20px"
               }
            },
            computed:{
                styles1 :function(){
                    return{
                        backgroundColor:this.color                        
                    }
                }
            },
            methods:{
                change:function(){
                    if(this.color == "yellow"){
                        this.color = "red";
                    }else{
                        this.color = "yellow";
                    }
                }
            }
        })
    </script>
</body>

</html>

9 样式变换 class

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <style>
    .shape{
        height: 150px;
        width:150px;
        float: left;
        margin: 10px;
    }
    .circle{
        background:red;
        border-radius: 50%;
    }
    .square{
        background-color:blue;
    }
    .triangle{
        width: 0;
        height: 0;
    }
    /* 上三角 */
    .up{
        border-left: 100px solid transparent;
        border-right: 100px solid transparent;
        border-bottom: 150px solid orange;
    }
    /* 下三角 */
    .down{
        border-left: 100px solid transparent;
        border-right: 100px solid transparent;
        border-top: 150px solid green;
    }
    .animation{
        animation: strentch 1.0s ease-out;
    }
    @keyframes strentch{
        0%{
            transform: scale(0.3);
        }
        100%{
            transform: scale(1)
        }
    }
    </style>
</head>
<body>
    <div id="app">
        <!-- 通过显示隐藏class切换效果 -->
        <!-- <div v-for = "shape in shapes" class = "shape" v-bind:class = "{circle:shape.isRound,square:!shape.isRound}"></div> -->
         <!-- 通过改变类名切换效果 -->
        <div v-for = "shape in shapes" class = "shape" v-bind:class = "[shape.shape,shape.direction?shape.direction:'',{animation:shape.animation}]"></div> 
        <!-- v-bind:class  可以简写为:class -->
        <!-- v-on:click 可以简写为@click -->
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                // 显示隐藏class
                // shapes:[
                //     {isRound:true},
                //     {isRound:false}
                // ]
                // 通过类名显示
                shapes:[
                    {shape:'circle',animation:true},
                    {shape:'square'},
                    {shape:'triangle',direction:"up",animation:true},
                    {shape:'triangle',direction:"down"}                    
                ]
            }
        })
    </script>
</body>

</html>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!