# Vuejs Note ## Lifecycle ![](https://i.imgur.com/BapqSti.png) * beforeCreate與created最大的差別在於data是否已取得,beforeCreate取得不到data的資料,所以很少用到; created由於是在畫面渲染之前的事件,所以通常會在這邊call api * beforeMount與mounted最大的差別在於是否取得`$el`,beforeMount取得不到`$el`,beforeMount會取得編譯前的原始碼,mounted則是已經轉換為html * beforeUpdate與updated的差別在於,當資料被轉換時,會觸發updated事件,beforeUpdate是資料已經被轉換但在畫面還沒被更新時觸發,兩個hook執行時間是一瞬間的 ## watch 變數改變時觸發事件 ``` watch: { firstName: { handler: function () { console.log("FirstName changed.") } } } ``` ## computed 當fullName被更動時會觸發set function,呼叫fullName會取得get function ``` computed: { fullName: { get: function () { return this.firstName + ' ' + this.lastName }, set: function (val) { let name = val.split(' ') this.firstName = name[0] this.lastName = name[1] } } } ``` ## props 用於component父傳子的參數的傳遞 tips: 當傳遞非字串的參數需用bind ``` # example.blade.php @extends('layouts.base') @section('content') <example-component props-test="123"></example-component> @endsection <script src="{{ mix('js/app.js') }}"></script> ``` ``` # ExampleComponent.vue data() { return { parentMessage: this.propsTest }; }, props: { propsTest: String }, ``` ## emit 用於component子傳父的參數的傳遞 ``` # parent <my-component :parent-message="message"></my-component> new Vue({ app: '#app', data: { message: 'hello' }, method: { selfUpdate(val) { this.$parent.$emit('update', val) } }, mounted() { this.$on('update', this.selfUpdate) } }) ``` ``` # child Vue.component('my-component', { template: '<span> {{ parentMessage }} <input v-model="message"></input> <button @click="updateText">Update</button> </span>', props: { parentMessage: String }, data() { return { message: this.parentMessage } }, method: { updateText() { this.$parent.$emit('update', this.message) } } }) ```