<!DOCTYPE html><html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="renderer" content="webkit"> <title>父子組件生命周期</title></head><body> <div id="app"> <p>{{parentData}}</p> <child message="hello子組件"></child> </div> <script src="https://cdn.bootcss.com/vue/2.5.15/vue.js"></script> <script> var app = new Vue({ el: '#app', data: { parentData: '父組件數(shù)據(jù)', }, beforeCreate() { console.log(`Parent--beforeCreate ${this.parentData} ${this.$el}`); }, created() { console.log(`Parent--created ${this.parentData} ${this.$el}`); }, components: { child: { template: `<div><p>{{message}}</p> <p>{{childrenData}}</p></div>`, props: { message: { type: String } }, data: function () { return { childrenData: '子組件數(shù)據(jù)' } }, beforeCreate() { console.log(this); console.log(`Child--beforeCreate ${this.message} ${this.childrenData} ${this.$el}`); }, created() { console.log(`Child--created ${this.message} ${this.childrenData} ${this.$el}`); }, } } }) </script></body>下面是輸出子組件在beforeCreate中讀取外部的傳入的變量時(shí)報(bào)錯(cuò)了,但是令我疑惑的是,上面可以輸出this的值,如果message沒有綁定到子組件上,最多就是輸出undefined值,而不應(yīng)該報(bào)錯(cuò)。難道是vue在內(nèi)部規(guī)定了子組件在beforeCreate的鉤子函數(shù)中不能讀取外部傳入的數(shù)據(jù),否則報(bào)錯(cuò)?
vue中子組件的beforeCreate鉤子函數(shù)中讀取父組件傳入的數(shù)據(jù)出現(xiàn)報(bào)錯(cuò)
動(dòng)漫人物
2019-03-20 17:19:28