Easy to understand - Getting Started Vue - 2

Examples of 1.Vue

<div id="exp">
    <div @click="handleClick">{{content}}</div>
</div>
</body>
<script>
    var vm = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp",
        data:{
            content:"hello world"
        },
        methods:{
            handleClick:function () {
                alert(this.content)
            }
        }
    });
</script>
// vm为一个实例,当执行vm.$destory()就会销毁这个实例。这样通过修改数据vm.$data.message = "123",
页面不会有相应的变化

2.Vue lifecycle hook

  • Life Cycle function is the function vue instance executed automatically at a certain point in time.
  • Note: The function of the life cycle and does not define the methods in.

img

  • Code
<div id="app"></div>
<script>
    var vm = new Vue({
        el:"#app",
        template:`<div>{{test}}</div>`,
        data:{
            test:"hello world"
        },
        // vue实例进行基本初始化之后会被执行
        beforeCreate:function () {
            console.log("beforeCreate");
        },
        // 初始化一些外部注入,和双向绑定,当此类操作完成会调用created
        created:function () {
            console.log("created");
        },
        // 在template页面挂载之前执行函数
        beforeMount:function () {
            // 此时this.$el 还没有被渲染
            console.log("beforeMount");
        },
        // 页面渲染完执行周期函数mounted
        mounted:function () {
            // 此时this.$el 已经被渲染了,
            console.log("mounted");
        },
        // 当调用vm.$destroy(),即将被销毁时候会执行
        beforeDestroy:function () {
            console.log("beforeDestory");
        },
        // 当前实例被销毁会被调用
        destroyed:function () {
            console.log("destroyed");
        },
        // 数据发生改变,vm.test='123'还没有重新渲染数据会被执行
        beforeUpdate:function () {
            console.log("beforeUpdate");
        },
        // 重新渲染数据会被执行vm.test='123'
        updated:function () {
            console.log("updated");
        }
    })
</script>

3. template syntax

1. The difference in expression

<div id="exp">
    {{name}}
</div>
或
<div>{{"my name is "+name}}</div>


<script>
    var vm = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp",
        data:{
            name:"James"
        }
    });
</script>

2.v-text

<div v-text="name"></div>
或
<div v-text="'my name is ' + name"></div>
<script>
    var vm = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp",
        data:{
            name:"James"
        }
    });
</script>

3.v-html

<div v-html="name_html"></div>
var vm = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp",
        data:{
            name_html:"<h1>James</h1>"
        }
    });

4.v-on

5.v-bind

4. Calculation listener properties and

1. Calculation Properties

  • The so-called attribute calculation, by calculating come below fullName defined by the function within the computed obtained.
var vm = new Vue({
    el:"#exp",
    data:{
        firstName:"Dell",
        lastName:"Lee"
        age:20
    },
    computed:{
        fullName:function () {
            console.log("计算一次")
            return this.firstName + " " + this.lastName
        }
    }
});
  • Cache attribute is calculated, by the above fullName firstName and lastName spliced ​​into, as firstName and lastName does not change, such as changing only the Age, is not printed "computed once", because the internal cache attributes are calculated, for improve performance, but firstName or lastName changed, it will print "computing time", recalculated once.
  • Compared to methods such as methods, when age changes, will recall fullName again, it 计算属性is more efficient:
methods:{
    fullName:function () {
    return this.firstName + " " + this.lastName
    }
},

2. Listener

  • By listening watch firstName and lastName change, if the data changes will perform the function of listening watch, if not changed will not be performed. And the listener properties are calculated cache concept, but written by the watch listener code is more complex:
watch:{
    firstName: function () {
        this.fullName = this.firstName + " " + this.lastName
    },
    lastName: function () {
        this.fullName = this.firstName + " " + this.lastName
    },
},
  • So the best recommendation: Calculate Properties> Listener> methods

3. Calculate property setter and getter

  • computed not only write the get method, you can also write the set method to set the value, but we usually only get to write method, noted that the method requires passing a set value.
computed:{
    fullName:{
        // 当取 fullName 会执行此方法
        get:function () {
        return this.firstName + " " + this.lastName
        },
        // 当设置fullName 会执行此方法
        set:function (value) {
        var arr = value.split(" ");
        this.firstName = arr[0];
        this.lastName = arr[1];

        console.log(value)
        }
    }
}

Style of binding 5.vue

  • In the process we write the page, DOM will add some style, then how to add style Vue

Mode 1: class object is bound

<style>
    .activated {
        color:red;
    }
</style>
<div id="exp">
    <div @click="handleDivClick" :class="{activated:isActivated}">{{text}}</div>
</div>

<script>
    var vm = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp",
        data:{
            text:"hello world",
            isActivated:false
        },
        methods:{
            handleDivClick:function () {
                this.isActivated = ! this.isActivated
            }
        }
    });

Option 2: an array of ways

<div id="exp2">
    <div @click="handleDivClick" :class="[activated,]">{{text}}</div>
</div>


var vm2 = new Vue({
    // el限制一个vue实例的管理范围。
    el:"#exp2",
    data:{
        text:"hello world",
        activated:""
    },
    methods:{
        handleDivClick:function () {
            this.activated = this.activated === "activated" ? "" : "activated"
        }
    }
});

Mode 3: style change style object bindings

<div id="exp3">
    <div @click="handleDivClick" :style="styleObj">{{text}}</div>
</div>

<script>
    var vm3 = new Vue({
        // el限制一个vue实例的管理范围。
        el:"#exp3",
        data:{
            text:"hello world",
            styleObj:{
                color:"black"
            }
        },
        methods:{
            handleDivClick:function () {
                this.styleObj.color = this.styleObj.color === "black" ? "red" : "black";
            }
        }
    });

</script>

Mode 4: style change style array binding

<div @click="handleDivClick" :style="[styleObj,{fontSize:'40px'}]">{{text}}</div>

6.Vue conditions rendering

1.v-if

<div v-if="show">{{message}}</div>

2.v-show

<div v-show="show">{{message}}</div>
  • The difference between them is that, v-show is already rendering the page out, but coupled with the display: none, and v-if not rendered on the page.
var vm = new Vue({
    // el限制一个vue实例的管理范围。
    el:"#exp",
    data:{
        show:false,
        message:"hello world"
    }
});
  • When the input terminal: vm.show = true, they will be displayed. When removing the tags often display, v-show is clearly more efficient. Because it would not want the same v-if, constantly created and destroyed. Conversely v-if more appropriate.

3.v-if-else / v-else

  • V-else
<div id="exp">
    <div v-if="show">{{message}}</div>
    <div v-else>Bye world</div>
</div>
  • v-else-if
<div id="exp">
    <div v-if="show === 'message'">{{message}}</div>
    <div v-else-if="show ==='count'">1</div>
    <div v-else>Bye world</div>
</div>
  • v-if, v-else, v-else-if binding label must be put together to write, I can not fail

Use 4.key value

  • Using key values ​​is necessary
<div id="app">
    <div v-if="show">
        用户名: <input type="text" key="username">
    </div>
    <div v-else>
        邮箱名: <input type="text" key="email">
    </div>
</div>
<script>
    //每个元素标签设置一个key值, 表示它是唯一标签,如果2个key不一样则不会服用原来元素标签
    // 虚拟dom算法用的内容
    var app = new Vue({
        el:"#app",
        data:{
            show:false
        }
    })
</script>

List 7.Vue in rendering v-for

  • Based on the use of
<div id="exp">
    <div v-for="(item,index) of list">
        {{item}}------{{index}}
    </div>
</div>
var vm = new Vue({
    // el限制一个vue实例的管理范围。
    el:"#exp",
    data:{
        list:[
            "hello,",
            "James",
            "nice",
            "to",
            "meet",
            "you"
        ]
    }
});
  • In order to improve cycling performance will give v-for tag a unique key value, the example you can write:
<div v-for="(item,index) of list" :key="index">
  • But often returned by the backend data items are similar to the following types:
list:[
    {id:001102,text:"hello"},
    {id:029303,text:"James"},
    ......
]
  • You can bind only key value in v-for
<div v-for="(item,index) of list" :key="item.id">
  • When we operate the array, not by such an array subscript Add: list[i]={id:03957569,text="bye"}only by providing as follows vue of:

    • Mode 1:
    push
    pop
    shift
    unshift 
    splice
    sort
    reverse
    • Option 2:
    改变数组的引用

placeholder template

  • Template placeholders that can help us by some elements of the package template placeholder, but in the cycle, and not really to be rendered on the page.

  • Loop array

<template v-for="(item,index) of list" 
:key="item.id">
    <div>
        {{item.text}}
    </div>
    <span>
        {{index}}
    </span>
</template>
  • Recycling target
<div id="app">
    <div v-for="(item,key,index) of userInfo">
        {{item}}---{{key}}---{{index}}
    </div>
</div>

<script>
    var app = new Vue({
        el:"#app",
        data:{
            userInfo:{
                name:"James",
                age:28,
                gender:"male",
                salary:"secret"
            }
        }
    });
</script>

8. added: Vue set method which

  • Increased data objects
//app为一个实例
app.$set(app.userInfo,"address","beijing")
  • Increase the array of data
vm.$set(vm.list,2,"wawawawaw")

Small summary:

  • Changing the mode data in the array

    改变数组的引用
    使用数组的变异方法
    set方法
  • Changing the mode data in the object

    改变对象的引用
    set方法

Guess you like

Origin www.cnblogs.com/xujunkai/p/12229978.html