1. 建立組件:components > Home.vuevue
<template> <div> <p class="first">我是Home組件:{{msg}}</p> <button @click="changeFist">click</button> </div> </template> <script> export default { name: "Home", data(){ return{ msg:"Hello World!", } }, methods:{ changeFist:function(){ this.msg="被點擊了" } }, //組件的生命週期函數 beforeCreate() { console.log("Home組件被建立以前"); }, created() { console.log("Home組件建立完成"); }, beforeMount(){ console.log('模板編譯以前3'); }, mounted(){ /*請求數據,操做dom , 放在這個裏面 mounted*/ console.log('模板編譯完成4'); }, beforeUpdate(){ console.log('數據更新以前'); }, updated(){ console.log('數據更新完畢'); }, beforeDestroy(){ /*頁面銷燬的時候要保存一些數據,就能夠監聽這個銷燬的生命週期函數*/ console.log('實例銷燬以前'); }, destroyed(){ console.log('實例銷燬完成'); } } </script> // scoped 規定了樣式只針對本組件。若是不加,則對於引用該組件的全部組件都應用樣式。 <style scoped> p{ color: #42b983; } </style>
根組件:App.vueapp
<template> <div id="app"> <p>我是主組件App</p> <button @click="destoryHome">點我{{actionHome}}Home組件</button> /*4. 在模板中使用*/ <v-home v-if="flag"></v-home> </div> </template> <script> //2.引入組件 import Home from "./components/Home" export default { name: "app", components: { //3. 掛載組件 "v-home": Home, }, data() { return { actionHome: "卸載", flag: true } }, methods: { destoryHome: function () { this.flag = !this.flag; if (this.flag) { this.actionHome = "卸載" } else { this.actionHome = "加載" } } }, } </script> <style> </style>