美文网首页Vuevue
第3章 Vue 基础精讲

第3章 Vue 基础精讲

作者: 读书的鱼 | 来源:发表于2019-05-19 09:48 被阅读135次
    3-1 Vue实例

    vue实例是根实例,组件也是vue实例,所以说页面是由很多vue实例组成的
    .data(): 以开头的指的是vue实例的属性或方法 vm.destroy():用于销毁vue实例,但是之前的数据和方法并没有被销毁

    var app = new Vue({
      el:'#root',
      data:{
        message:'hello world'
      },
      methods: {
        handleClick(){},
      },
      watch:{
    
      },
      computed:{
    
      }
    })
    
    3-2 Vue实例生命周期
    //生命周期函数就是vue实例在某个时间点自动执行的函数
    var app = new Vue({
            el:'#root',
            data:{
               inputValue:'' 
            },
            beforeCreate: function () {
                console.log('beforeCreate');
            },
            created: function () {
                console.log('created');
            },
            beforeMount: function () {
                console.log(this.$el);
                console.log('beforeMount');
            },
            mounted: function () {
                console.log(this.$el);
                console.log('mounted');
            },
            beforeDestroy: function () {
                //app.$destroy()
                console.log('beforeDestroy');
            },
            destroyed: function () {
                console.log('destroyed');
            },
            beforeUpdate: function () {
                //app.$data.inputValue = 1
                console.log('beforeUpdate')
            },
            updated: function () {
                console.log('updated')
            }
    })
    
    3-3 Vue的模版语法

    插值表达式{{}} : 用{{输入的值}}
    v-指令 写的是js表达式
    v-text 就是innertext 其实就是 {{}}
    v-html 就是innerhtml
    v-指令 后面除了可以写js名称还可以加字符串,插值表达式也可以写字符串

    var app = new Vue({
          el: '#root',
          data: {
              name: 'hello',
              bigName: '<h1>hello</h1>'
          }
    })
    
    {{name + ' world'}}
    <div v-text="name + ' world' "></div>
    <div v-html="name + ' world' "></div>
    
    ps:v-html 会对bigName进行转义,字体变成h1字体大小,而不会出现标签
    
    3-4 计算属性、方法与侦听器

    计算属性
    computed属性,因为他是属性,所以在用插值表达式取值的时候不用加括号
    computed:内置变量缓存的功能,当data里面age变量更改时,如果不是计算属性内边的变量更改,那么他就不会渲染computed内部的变量

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        {{fullName}}
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                firstName: 'sunny',
                lastName: 'fan',
                age: 28
            },
            //计算属性:内置缓存(firstName、lastName)
            computed: {
                fullName: function () {
                    console.log('计算了一次');
                    return this.firstName + " " + this.lastName
                }
            }
        })
    </script>
    </body>
    </html>
    

    methods方法
    因为是方法,所以插值表达式要用括号取值,
    他不具有缓存变量的功能

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        {{fullName()}}
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                firstName: 'sunny',
                lastName: 'fan'
            },
            methods: {
                fullName: function () {
                    console.log("计算了一次")
                    return this.firstName + " " + this.lastName
                }
            }
        })
    </script>
    </body>
    </html>
    

    侦听器

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>侦听器</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        {{fullName}} {{age}}
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                firstName: 'sunny',
                lastName: 'fan',
                fullName: 'sunny fan',
                age: 28
            },
            watch: {
                firstName: function () {
                    console.log('计算了一次');
                    this.fullName = this.firstName + " " + this.lastName
                },
                lastName: function () {
                    console.log('计算了一次');
                    this.fullName = this.firstName + " " + this.lastName
                }
            }
        })
    </script>
    </body>
    </html>
    

    总结:我们可以通过methods、computed、watch来实现fullName显示的问题
    computed和watch都具备缓存的功能
    但是从代码量的编写程度来看,computed属性会更加方便和便捷一些。

    3-5 计算属性的getter和setter

    computed属性当中有两个方法,分别是:get 和 set

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>getter和setter</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <body>
    <div id="root">
        {{fullName}} {{age}}
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                firstName: 'sunny',
                lastName: 'fan',
                age: 28
            },
            computed: {
                fullName: {
                    get: function () {
                        return this.firstName + " " + this.lastName
                    },
                    set: function (value) {
                        console.log(value);
                        var arr = value.split(" ");
                        this.firstName = arr[0];
                        this.lastName = arr[1];
                    }
                }
            }
        })
    </script>
    </body>
    </body>
    </html>
    
    3-6 Vue中的样式绑定

    class的对象绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>class的对象绑定</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
        <style>
            .activated {
                color: red;
            }
        </style>
    </head>
    <body>
    <body>
    <div id="root">
        <div @click="handleChangeColor" :class="{activated:isActivated}">
            hello world
        </div>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                isActivated: false
            },
            methods: {
                handleChangeColor: function () {
                    this.isActivated = !this.isActivated
                }
            }
        })
    </script>
    </body>
    </body>
    </html>
    

    class的数组绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>class的数组绑定</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
        <style>
            .activated-one {
                font-size: 20px;
            }
    
            .activated {
                color: red;
            }
        </style>
    </head>
    <body>
    <div id="root">
        <div @click="handleChangeColor" :class="[activated,activatedOne]">hello world</div>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                activated: '',
                activatedOne: 'activated-one'
            },
            methods: {
                handleChangeColor: function () {
                    this.activated = this.activated === 'activated' ? "" : "activated"
                }
            }
        })
    </script>
    </body>
    </html>
    

    style对象绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>style对象绑定</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        <div @click="handleChangeColor" :style="styleObj">hello world</div>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                styleObj: {
                    color: 'black'
                }
            },
            methods: {
                handleChangeColor: function () {
                    this.styleObj.color = this.styleObj.color === 'black' ? 'red' : 'black'
                }
            }
        })
    </script>
    </body>
    </html>
    

    style的数组绑定

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>style数组绑定</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        <div @click="handleChangeColor" :style="[styleObj,{fontSize:'30px'},styleOne]">hello world</div>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                styleObj: {
                    color: 'black'
                },
                styleOne: {
                    fontWeight: 'bold'
                }
            },
            methods: {
                handleChangeColor: function () {
                    this.styleObj.color = this.styleObj.color === 'black' ? 'red' : 'black'
                }
            }
        })
    </script>
    </body>
    </html>
    
    3-7 条件渲染

    v-if 、v-else-if、v-else

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>V-if</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        <h5>实例一:v-if</h5>
        <template v-if="isShow">
            hello world
        </template>
        <button @click="handleChange">{{toggleText}}</button>
        <hr>
        <h5>实例二:v-else</h5>
        <div v-if="isShowTwo">
            要是我显示
        </div>
        <div v-else>
            要么你显示
        </div>
        <button @click="handleChangeRole">切换显示</button>
        <hr>
        <h5>实例三:v-else-if</h5>
        <div v-if="status==='A'">
        A
        </div>
        <div v-else-if="status==='B'">
            B
        </div>
        <div v-else-if="status==='C'">
            C
        </div>
        <div v-else>
            其他
        </div>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                isShow: false,
                toggleText: '显示',
                isShowTwo: true,
                status: 'A'
            },
            methods: {
                handleChange: function () {
                    this.isShow = !this.isShow;
                    this.toggleText = this.toggleText === '显示' ? '隐藏' : '显示'
                },
                handleChangeRole: function () {
                    this.isShowTwo = !this.isShowTwo;
                }
            }
        })
    </script>
    </body>
    </html>
    

    key 管理可复用的元素
    当切换两个input输入框的时候,为了不然input框的输入内容被占用,所以我们通过设置input的key值来解决这个问题

    <template v-if="loginType === 'username'">
      <label>Username</label>
      <input placeholder="Enter your username" key="userName-input">
    </template>
    <template v-else>
      <label>Email</label>
      <input placeholder="Enter your email address" key="email-input">
    </template>
    

    v-show
    v-show很相似,只要设置值为true则显示

    v-if和v-show的区别

    • v-show不能和v-else 和 v-else-if结合使用
    • v-show 不管是ture还是fasle div元素都会渲染出来(false style的display:none),如果如果有频繁的切换,我们会首选v-show,减少对dom的频繁操作
    3-8 Vue列表渲染

    v-for
    <li v-for="(item,index) in list" :key="index">{{index}}--{{item}}</li>
    <li v-for="(item,key,index) of userInfo" :key="index">{{key}}-{{item}}-{{index}}</li>

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>列表渲染</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
    <div id="root">
        <ul>
            <li v-for="(item,index) in list" :key="index">{{index}}--{{item}}</li>
        </ul>
        <ul>
            <li v-for="(item,key,index) of userInfo" :key="index">{{key}}-{{item}}-{{index}}-</li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#root',
            data: {
                list: [
                    'hello',
                    'world'
                ],
                userInfo: {
                    name: 'sunny',
                    age: 29
                }
            }
        })
    </script>
    </body>
    </html>
    

    template可以当一个空标签做为for循环渲染,而这个template不会渲染到dom里面

    <ul>
      <template v-for="item in items">
        <li>{{ item.msg }}</li>
        <li class="divider" role="presentation"></li>
      </template>
    </ul>
    

    为了防止子组件循环渲染出现dom结构不对的情况,我们一般会通过is来给子组件命名

    //html
     <table>
        <tbody>
          <tr is="row" v-for="item in list" :title="item"></tr> //这个地方调用is属性
       </tbody>
    </table>
    
    //js
     Vue.component('row', {
            props: ['title'],
            template: '<tr><td>{{title}}</td></tr>'
    });
    var app = new Vue({
            el: '#root',
            data: {
                list: [
                    'hello',
                    'world'
                ]
            }
        })
    
    更改数组值方法有哪些?

    1.变异方法
    push()、 pop()、 shift()、unshift()、splice()、sort()、reverse()
    2.替换数组
    当也可以创建一个新的数组,在通过
    filter()、concat()、slice()
    更改原始数组的值,再把更改后的数组替换旧的数组
    3.set或者$set方法

    Vue.set(app.userInfo,'age',22)
    //或者
    vm.$set(app.userInfo,'age',22)
    

    4.Object.assign()或者_.extend()

    vm.userInfo = Object.assign({},vm.userInfo,{
      sex:'男',
      email:'fx35792@163.com'
    })
    

    ps:不可以通过数组下标去更改数组的值

    var vm = new Vue({
      data: {
        items: ['a', 'b', 'c']
      }
    })
    vm.items[1] = 'x' // 不是响应性的
    vm.items.length = 2 // 不是响应性的
    

    3-9 Vue事件处理

    监听事件、方法处理、内联处理器中的方法

    1.监听事件

    通过v-on指令监听DOM事件,并在触发时运行一些 JavaScript 代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>监听事件</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    </head>
    <body>
        <div id="root">
            <button v-on:click="counter+=1">add 1</button>
            <p>The button above has been clicked {{counter}} times.</p>
        </div>
        <script type="text/javascript">
        var app = new Vue({
            el: '#root',
            data: {
                counter: 0
            }
        })
        </script>
    </body>
    </html>
    
    2.事件处理方法

    但是在开发的过程中,有时候直接把 JavaScript 代码写在 v-on 指令中是不可行的。因此 v-on 还可以接收一个需要调用的方法名称

    <div id="root">
        <button v-on:click="greet">greet</button>
    </div>
    <script>
        const app = new Vue({
            el: '#root',
            data: {
                name: 'sunny'
            },
            methods: {
                greet: function (event) {
                    console.log(`hello ${this.name}`)
                    if (event) {
                        console.log(event.target.tagName)
                    }
    
                }
            }
        })
    </script>
    
    3.内联处理器中的方法

    除了直接绑定到一个方法,也可以在内联 JavaScript 语句中调用方法:

    <button v-on:click="say('hi')">say hi</button>
    <button v-on:click="say('hello')">say hello</button>
    
    const app = new Vue({
            el: '#root',
            data: {
                name: 'sunny'
            },
            methods: {
                say: function (val) {
                    console.log(`${this.name} ${val}`)
                }
            }
        })
    

    方法总通过传递参数$event,可以原始的DOM

    <button v-on:click="warning('please input number',$event)">warning</button>
    const app = new Vue({
            el: '#root',
            data: {},
            methods: {
                warning: function (val, event) {
                    if (event) event.preventDefault();
                    console.log(val)
                }
            }
        })
    
    4.事件修饰符

    我们在开发个过程中经常调用一些
    event.preventDefault() //阻止事件的默认行为
    event.stopPropagation() //阻止冒泡的行为

    而vue为了更好的让我们关注业务逻辑代码的编写,它封装了很多v-on修饰符来帮助我们完成上面那些工作。

    • stop //event.stopPropagation()
    • prevent //event.preventDefault()
    • capture
    • self
    • once
    • passive

    更多

    上一篇:第2章 Vue起步
    下一篇:第4章 深入理解Vue组件
    全篇文章:Vue学习总结
    所有章节目录:Vue学习目录

    相关文章

      网友评论

        本文标题:第3章 Vue 基础精讲

        本文链接:https://www.haomeiwen.com/subject/gqyfzqtx.html