search
HomeWeb Front-endVue.jsThis article talks about the three stages of the Vue component life cycle (creation, running and destruction)

This article will give you a detailed introduction to the three stages of Vue component life cycle: creation phase, running phase and destruction phase. I hope it will be helpful to everyone!

This article talks about the three stages of the Vue component life cycle (creation, running and destruction)

Component Life Cycle

Life Cycle(Life Cycle) refers to A component is created from -> runs -> destroys the entire Stage emphasizes a period of time. [Related recommendations: vuejs video tutorial, web front-end development]

Life cycle function: It is composed of vue framework The provided built-in functions will be automatically executed in sequence along with the component's life cycle.

Create phase

beforeCreate phase

When we initialize events and life cycle functions, the component’s props/data/methods has not been created yet and is in an unavailable state.

<script>
export default {
    props:[&#39;info&#39;],
    data(){
        return {
            message:&#39;hello test&#39;
        }
    },
    methods:{
        show(){
            console.log(&#39;调用了 Test 组件的 show 方法&#39;);
        }
    },
    // 创建阶段的第一个生命周期
    beforeCreate(){
        console.log(this.info); //props
        console.log(this.message); //data
        this.show() //methods
    },
}
</script>

Because props/data/methods cannot be used but when I call it, all consoles report errors.

##created phase

We have initialized

props, data, methods, the component’s props/data/methods have been created. They are all in a usable state, but the template structure of the component has not yet been completed!

<script>
export default {
    props:[&#39;info&#39;],
    data(){
        return {
            message:&#39;hello test&#39;
        }
    },
    methods:{
        show(){
            console.log(&#39;调用了 Test 组件的 show 方法&#39;);
        }
    },
    // 创建阶段的第二个生命周期函数
    created(){
        console.log(this.info);
        console.log(this.message);
        this.show()
    }
}
</script>

The created life cycle function is very commonly used. In daily project development, methods in methods are often called in it,

Request server data, and transfer the requested data to data for use when the template is rendered!

<template>
  <div>
    <h2 id="test组件-nums-length">test组件--{{nums.length}}</h2>
  </div>
</template>
<script>
export default {
    props:[&#39;info&#39;],
    data(){
        return {
            message:&#39;hello test&#39;,
            nums:[]
        }
    },
    methods:{
        show(){
            console.log(&#39;调用了 Test 组件的 show 方法&#39;);
        },
        initlist(){
            const xhr = new XMLHttpRequest()
            xhr.addEventListener(&#39;load&#39;,()=>{
                const result = JSON.parse(xhr.responseText)
                console.log(result);
                this.nums = result.data
            })
            xhr.open(&#39;GET&#39;,&#39;请求的接口&#39;)
            xhr.send()
        }
    },
    created(){
        this.initlist()
    }
}
</script>
<style>
    div{
        background-color: #f00;

    }
</style>

beforeMount stage:

Based on

data and template , is compiled in memory to generate HTML structure. The compiled HTML structure in memory will be rendered into the browser. At this time, the browser does not yet have the DOM structure of the current component.

<template>
  <div>
    <h2 id="test组件-nums-length">test组件--{{nums.length}}</h2>
  </div>
</template>
<script>
export default {
    props:[&#39;info&#39;],
    data(){},
    methods:{},
    beforeCreate(){},
    created(){},
    beforeMount(){
        console.log(&#39;beforeMount&#39;);
        const dom = document.querySelector(&#39;#myid&#39;)
        console.log(dom);
    }
}
</script>

mounted stage:

Use

memoryThe HTML structure generated by compilation in replaces the DOM element specified by the el attribute. The HTML structure in the memory has been successfully rendered into the browser. At this time, the browserAlready contains the DOM structure of the current component.

<template>
  <div>
    <h2 id="test组件-nums-length">test组件--{{nums.length}}</h2>
  </div>
</template>
<script>
export default {
    mounted(){
        const dom = document.querySelector(&#39;#myid&#39;)
        console.log(dom);
    }
}
</script>

vue calls mounted after it completes template parsing and puts the real DOM element it first encountered on the page (mounting is completed).

<template>
  <div>
    <h2 id="欢迎学习Vue">欢迎学习Vue</h2>
  </div>
</template>
<script>
export default {
    data(){
        return {
            opacity:1
        }
    },
    mounted(){
        setInterval(()=>{
            //我们在使用箭头函数时,this的指向mounted自动帮我们设置好是 vm 了
            this.opacity-=0.01
            if(this.opacity <= 0) this.opacity = 1
        },6)
    },
}
</script>

Running phase

The so-called running phase is the interaction between the user and the component

beforeUpdate阶段

这个函数的触发的必要前提是,我们修改了 data 里面的数据。将要(注意:仅仅是将要,还没有呢)根据变化过后最新的数据,重新渲染组件的模板结构

<template>
  <div>
    <h2 id="message">{{message}}</h2>
    <button>点击修改message值</button>
  </div>
</template>
<script>
export default {
    data(){
        return {
            message:&#39;hello test&#39;,
        }
    },
    beforeUpdate(){
        console.log(&#39;beforeUpdate&#39;); //说明:点击按钮修改data值才能触发这个函数
        console.log(this.message); //打印修改后的值
        const dom = document.querySelector(&#39;#myid&#39;)
        console.log(dom.innerHTML); //打印整个文本,但并没有出现我们修改后的值,说明页面并没有重新渲染
    }
}
</script>

updated阶段

已经根据最新的数据,完成了组件的DOM结构的重新渲染。注意:当数据变化之后,为了能操作到最新的 DOM 结构,必须把代码写到 updated 生命周期函数中。

<template>
  <div>
    <h2 id="message">{{message}}</h2>
    <button>点击修改message值</button>
  </div>
</template>
<script>
export default {
    props:[&#39;info&#39;],
    data(){
        return {
            message:&#39;hello test&#39;,
        }
    },
    updated(){
        console.log(&#39;updated&#39;); 
        console.log(this.message); //打印修改后的值
        const dom = document.querySelector(&#39;#myid&#39;)
        console.log(dom.innerHTML); //打印整个文本,但出现了我们修改后的值,说明页面被重新渲染
    }
}
</script>

销毁阶段

完全销毁一个实例。清理它(vm)与其它实例的连接,接绑它的全部指令及事件监听器。

beforeDestroy阶段

将要销毁此组件,此时尚未销毁,组件还处于正常工作状态。在这阶段一般做一些首尾工作。

<template>
  <div>
    <h2 id="message">{{message}}</h2>
    <button>点击修改message值</button>
  </div>
</template>
<script>
export default {
    props:[&#39;info&#39;],
    data(){
        return {
            message:&#39;hello test&#39;,
        }
    },
    beforeDestroy(){
        console.log(&#39;beforeDestroy&#39;);
    }
}</script>

destroyed阶段

销毁当前组件的数据侦听器、子组件、事件监听等,组件已经被销毁,此组件在浏览器中对应的DOM结构已被完全移除

直接暴力的将vm干掉,页面就不能再进行交互。设置透明的按钮也就作废了。

<template>
  <div>
    <h2 id="欢迎学习Vue">欢迎学习Vue</h2>
    <button>透明度设置为1</button>
    <button>点我停止变化</button>
  </div>
</template>
<script>
export default {
    data(){
        return {
            opacity:1
        }
    },
    methods:{
        stop(){
            // clearInterval(this.timer)
            this.$destroy()
        }
    },
    mounted(){
        // const dom = document.querySelector(&#39;#myid&#39;)
        // console.log(dom);
        console.log(&#39;mounted&#39;,this);
        this.timer = setInterval(()=>{
            console.log(&#39;setInterval&#39;);
            this.opacity-=0.01
            if(this.opacity <= 0) this.opacity = 1
        },6)
    },
    beforeDestroy(){
        clearInterval(this.timer)
        console.log(&#39;vm即将被销毁&#39;);
    }
}
</script>
<style>
    div{
        // background-color: #f00;

    }
</style>

1)销毁后借助Vue开发者工具看不到任何信息。

2)销毁后自定义事件会失效,但原生的DOM事件依然有效

3)一般不会在beforeDestroy操作数据,因为即使操作数据,也不会再触发更新流程了

总结

生命周期

1)又称:生命周期回调函数、生命周期函数、生命周期钩子。

2)含义:vue在关键时刻帮助我们调用一些特殊名称的函数。

3)生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。

4)生命周期函数中的this指向是 vm 或 组件实例对象。

常用的生命周期钩子

1)mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等(初始化操作)

2)beforeDestroy:清除定时器、绑定自定义事件、取消订阅消息等(收尾工作)

下面是实例生命周期的图表。你现在并不需要完全理解图中的所有内容,但以后它将是一个有用的参考。

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of This article talks about the three stages of the Vue component life cycle (creation, running and destruction). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)