vue生命週期:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeDestroy
- destroyed
這次先觀測 : beforeCreate created beforeMount mounted
測試代碼:
<!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://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{message}}</h1>
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Vue的生命週期'
},
beforeCreate: function() {
console.group('------beforeCreate創建前狀態------');
console.log("%c%s", "color:red" , "el : " + this.$el); //undefined
console.log("%c%s", "color:red","data : " + this.$data); //undefined
console.log("%c%s", "color:red","message: " + this.message)
},
created: function() {
console.group('------created創建完畢狀態------');
console.log("%c%s", "color:red","el : " + this.$el); //undefined
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
},
beforeMount: function() {
console.group('------beforeMount掛載前狀態------');
console.log("%c%s", "color:red","el : " + (this.$el)); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
},
mounted: function() {
console.group('------mounted 掛載結束狀態------');
console.log("%c%s", "color:red","el : " + this.$el); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
},
})
</script>
</html>
可以看到:
- beforeCreate :實例中的掛載點,數據項data都未初始化
- created : 掛載點(未),數據項data(已)
- beforeMount : 掛載點(已),數據項data(已),data中的message信息沒有被掛在到Bom節點中
- mounted : 掛載點(已),數據項data(已),data中的message信息已經被掛在到Bom節點中
【在todolist例子中,將在頁面刷新後,數據不丟失,在beforeMount週期內,初始化數據】
<template>
<div>
<div>
<input v-model="inputValue"/>
<button @click="handleSubmit">提交</button>
</div>
<ul>
<todoItem
v-for="(item,index) of list"
::key="index"
:content="item"
:index ="index"
@delete = "handleDelete"
></todoItem>
</ul>
</div>
</template>
<script>
import todoItem from './components/todoItem.vue'
export default {
components: {todoItem},
//以前data是一個對象,現在在vue-cli裏應該是一個函數,簡寫爲: data() {}
data : function() {
return {
inputValue: '',
list: []
}
},
beforeMount() {
//localStorage本地保存數據,實現刷新網頁數據不會丟失
const StoList = localStorage.getItem('list');
if(StoList) {
const isExist = StoList.length === 0 ? false : true;
if(isExist) {
this.list = StoList.split(",")
}
}
},
methods: {
handleSubmit () {
this.list.push(this.inputValue)
// this.list = [...this.list,this.inputValue]
this.inputValue = ''//讓輸入框爲空
localStorage.setItem('list', this.list)
},
handleDelete (index) {
this.list.splice(index,1)//從索引位置開始刪除,將該索引處的值刪除掉就好
localStorage.setItem('list', this.list)
}
}
}
</script>
<style>
</style>
效果:
刷新後: