Vue-3: life cycle, computed, watch, filter, virtual dom and diff algorithm

life cycle

The main stages of the Vue life cycle : 4 before, 4 ed, create, load, update, destroy

Remember to say the words:

Execute the first 4 life cycle hook functions for the first time,

The template is rendered when mounted,

The life cycle order of parent and child components (the first three in the parent component, the first four in the child component, and the fourth in the parent component)

 // 生命周期/*  */
    // 初始化阶段(不常用),拿不到data中的数据
    beforeCreate() {
        // 创建实例前
    },

    created() {
        // 发送ajax请求,获取数据,赋值data,渲染
    },
    // 挂载阶段
    beforeMount() {

    },
    // 可以拿到dom元素,进行性dom操作
    mounted() {

    },
    // 更新阶段 (触发它的更新,数据变化,dom元素新增或者删除)
    beforeUpdate() {

    },
    updated() {

    },
    // 销毁阶段
    // vue2:::
    // beforeDestroy(){

    // },
    // destroyed(){

    // }

    // vue3:::
    //  这两个钩子函数需要 触发页面的才可以看到执行
    //  可以在这个阶段,清除定时器,或者一些全局的函数
    //   想看到效果,需要销毁这个组件, 可以在父组件中销毁这个组件
    beforeUnmount() {

    },
    unmounted() {

    }

computed:{} computed attribute (total price +-*/)

  • // Handle complex logic for data processing in data (looks like a method, uses like an attribute, calculates an attribute)

  • Computational attributes will cache the processed results after processing the first data. As long as the dependent data remains unchanged, it will be read from the cache for future use.

  • Computed properties are cached and methods are executed as long as they are called (computed properties save performance)

  • Readable and unchangeable, get set can be changed and readable

    //1.只能读,不能写
    computed:{
        revserMsg(){
            console.log('烦死了');
            return this.msg.split('').reverse().join('')
        }
    }

    //2.这样写,可读可写
get **必选**:会在计算属性再第一次被调用或者是在依赖的数据改变之后会自动执行  
并且返回一个处理好的结果

set **可选**:set里面必须有一个形参  这个形参就是计算属性修改之后的值  
什么时候被调用:就是再计算属性处理好的值 被修改的时候调用

    computed: {
            // 这样写,可读不可写
            // fullName(){
            //    return
            // }

            // 这样写,可读可写
            fullName:{
                get(){
                    return this.first+this.las
                },
                set(val){
                    console.log(val);
                    this.first = val.split('')[0]
                    this.las = val.split('')[1]
                }
            }
        }

watch: {} listener: listen to the data in the data, and when the data data changes, it will trigger to execute some logic

  • Usage scenario: Perform asynchronous or expensive operations when data changes.

  • Watch does not support caching. When the corresponding property changes, the response is executed.

  • Use watch to listen to data changes in data. The attributes in watch must be the data that already exists in data at this stage.

  • 简写:
    watch:{
    	你要监听的data数据(newval,oldval){
    		你的逻辑
    	}
    }

1. The callback function executed when the data monitored by the handler method changes

2. The watch will not trigger on the first load. If we want to trigger, we must use the immedate attribute to enable the first load monitor

3, and the watch will not monitor the change of the object's property by default . If we want to monitor the change of the object's property, we can use deep

//监听器watch使用
    <div id="app">
        <!-- <input type="text" v-model="firsttext">
        +
        <input type="text" v-model="secondtext">
        =
        {
   
   {sumtext}} -->
        <input type="text" v-model="user.firsttext">
        +
        <input type="text" v-model="user.secondtext">
        =
        {
   
   {user.sumtext}}
    </div>

</html>
<script src="./lib/vue.global.js"></script>
<script>
    Vue.createApp({
        data() {
            return {
                // firsttext:'',
                // secondtext:'',
                // sumtext:''
                user: {
                    firsttext: '哈',
                    secondtext: '黑',
                    sumtext: ''
                }
            }
        },
        watch: {
            // // 简单写法(侦听器:侦听属性)
            // 1.
            // firsttext: function (newval,oldval) {
            //     this.sumtext = newval + this.secondtext
            //     console.log(this.newval);
            // },
            // secondtext: function(newval,oldval){
            //     this.sumtext = this.firsttext + newval
            // }

            // 2.打点写法,层次多麻烦
            // 'user.firsttext':function(newval,oldval){
            //     this.user.sumtext = newval + this.user.secondtext
            // },
            // 'user.secondtext':function(newval , oldval){
            //     this.user.sumtext = this.user.firsttext + newval
            // }


            // 复杂写法(深层侦听器:懒执行,添加立即执行即可解决)
            user: {
                // 开启深层监听器
                deep: true,
                // 强制回调函数立即执行
                immediate: true,
                // handler监听的数据改变的时候执行的回调函数
                handler(newval,oldval){
                    this.user.sumtext = newval.firsttext + newval.secondtext
                }
            }
        }
    }).mount('#app')

</script>

filter: {} filter: process some data (not in V3, computed properties can be replaced)

Partial filter: Format and display the content without changing the original data, but it will only take effect on the data within its own range


    <div id="app">
        <!-- {
   
   { data数据 | 过滤器名}} -->
        {
   
   {time | newTime}}<br>
        <!-- {
   
   { data数据 | 过滤器名(传递的值可以多个)}} -->
        {
   
   {msg | newMsg(' --- ','爱')}}<br>
        <!-- {
   
   { data数据 | 过滤器名(传递的值可以多个) | 对前边的数据操作}} -->
        {
   
   { msg | newMsg(' --- ','爱') | newNewMsg }}
    </div>
<script src="./lib/vue.js"></script>
<!-- <script src="./lib/vue.global.js"></script> -->
<script>
    let app = new Vue({
        data() {//数据
            return {
                time: 1314521,
                msg: 'hello world'
            }
        },
        methods: {//方法

        },
        computed: {//计算属性

        },
        watch: {//侦听器

        },
        filters: {//过滤器
            
            newTime(val) {// 传进的前一个值。默认值val
                // 将时间戳转换成日期对象,转换成日期对象
                return new Date(val).toLocaleString()
            },

            // newMsg(){
            //     return '哈哈哈哈哈'
            // },
            newMsg(val) {
                return val.split('').reverse().join('')
            },
            newMsg(val,x,y) {//val是默认的,是你处理的元素,x是reverseMsg的参数...val后可传递多个
                return val.split('').reverse().join(x)+y
            },
            newNewMsg(){
                return '哈哈哈哈哈'
            }
        },
        compontent: {//全局组件
            compontents: {//局部组件:带s
            }
        }
    })
    app.$mount("#app")
</script>

Global filter: Formatting and displaying content without changing the original data will take effect for all location data under the current project

        // 全局过滤器filter
        // Vue.filter("过滤器的名字",(你要过滤器的数据)=>{
        //     return 你的逻辑
        // })
        Vue.filter("xiaoming",(val)=>{
            if(val.length>3){
                return val.substr(0,3)+"..."
            }else{
                return val
            }
        })

v-for and virtual dom and diff algorithms

  • v-forThe default behavior is to try to modify the element in-place instead of recreating it (in-place update)

    • How to operate dom: cycle out the new virtual DOM structure, compare with the old virtual DOM structure, try to reuse tags to update the content in place

  • virtual dom

    • In fact, it is just a layer of abstraction to the real DOM. The tree is based on JavaScript objects (VNode nodes), and the properties of the objects are used to describe the nodes. Finally, the tree can be mapped to the real environment through a series of operations

    • Advantages: Improve the performance of DOM update, operate the real DOM infrequently, find the changed part in memory, and then update the real DOM (patch)

      DOM is very slow, its elements are very large, and the performance problems of the page are mostly caused by real DOM nodes caused by DOM operations. Even the simplest div contains many attributes

      The cost of operating the DOM is still expensive, and frequent operations will still cause page freezes, which will affect the user experience, so use virtual dom

    • Implementation ideas: The context (meaning of attributes) options of all objects in Vue point to the Vue instance, so in Vue, the tags in the #app template must be processed by Vue into virtual DOM objects before being rendered and displayed on the real DOM page

  • diff algorithm

    • How does the diff algorithm compare the old and new virtual DOM?:

  1. peer comparison

  2. The root element has changed: delete and rebuild the DOM tree

  3. The root element has not changed, but the attributes have changed: DOM reuse, only update attributes

    • Does v-for have: key=" "

      • The unique identifier of the virtual DOM

      • Without a key, v-for will maximize in-place updates and reuse elements of the same type

      • With the key attribute, the diff algorithm will compare according to your key value: it is equivalent to direct insertion, which improves the update efficiency

Guess you like

Origin blog.csdn.net/qq_60839348/article/details/130648710