1. 程式人生 > >Vue學習之旅----元件及生命週期

Vue學習之旅----元件及生命週期

<template>
  <div id="app">
    <v-home></v-home>
    <v-news></v-news>
    <router-view />
  </div>
</template>

<script>
import Home from './components/Home.vue'
import News from './components/News.vue'
// 生命週期函式:元件掛載以及元件更新元件銷燬的時候觸發的一系列的方法,這些方法就叫做生命週期函式
// 引入
export default {
  data () {
    return {
      name: 'App'
    }
  },
  // 掛載
  components: {
    'v-home': Home,
    'v-news': News
  },
  mounted () { // 請求資料,操作dom , 放在這個裡面  mounted
    console.log('模板編譯完成4')
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
<template>
  <div>
    {{msg}}
    <button @click="setMsg()">改變msg</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      msg: '生命週期函式'
    }
  },
  methods: {
    setMsg () {
      this.msg = '我是改變後的資料'
    }
  },
  beforeCreate () {
    console.log('例項建立前1')
  },
  created () {
    console.log('例項建立完成2')
  },
  beforeMount () {
    console.log('模版編譯之前3')
  },
  mounted () { // 請求資料,操作dom , 放在這個裡面  mounted
    console.log('模板編譯完成4')
  },
  beforeUpdate () {
    console.log('資料更新之前')
  },
  updated () {
    console.log('資料更新完畢')
  },
  beforeDestroy () { // 頁面銷燬的時候要儲存一些資料,就可以監聽這個銷燬的生命週期函式
    console.log('例項銷燬之前')
  },
  destroyed () {
    console.log('例項銷燬完成,一般做資料儲存工作')
  }
}
</script>
<style>
</style>
<template>
  <div>Home
    <button @click="getHomeData()">Home</button>
    <v-header></v-header>
    <v-life v-if="flag"></v-life>
    <button @click="flag=!flag">掛載和解除安裝元件</button>
  </div>
</template>
<script>
import Header from './Header.vue'
import Life from './Life.vue'
export default {
  data () {
    return {
      msg: 'home',
      flag: true
    }
  },
  components: {
    'v-header': Header,
    'v-life': Life
  },
  methods: {
    getHomeData () {
      alert('home')
    }
  }
}
</script>
<style lang="css" scope>
</style>
<template>
  <div>
    <h2>頭部元件</h2>
  </div>
</template>
<script>
export default {
  data () {
    return {}
  }
}
</script>
<style>
</style>