Vue生命周期一篇就够了和组件注册和复用功能实现

大家一定要学会看官方的文档,它是一个最好的文档

Vue的生命周期

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<script src="js/vue.min.js"></script>

<body>

<div id="container">

<label v-once>{
   
   {str}}</label>

<label for="">{
   
   {str}}</label>

</div>

 <script type="text/javascript">

new Vue({
      
      

  el:"#container",

  data:{
      
      

​    str:'从前有座山'

  },

  beforeCreate() {
      
      //1.data初始化之前,不可以操作data},

  created(){
      
      // 2.data初始化之后执行,模板加载之前,可以修改和获取data中的值

​    console.log(str);this.str="山里有座庙";

 },

  beforeMount() {
      
      // 3.模板加载之后,数据初始化(挂载)渲染之前,可以修改和获取data中的值this.str="庙里有口井";





  },

  mounted() {
      
      // 挂载之后执行,可以对data数据进行修改,但是不会影响v-once数据的渲染this.str="井里有只蛙";

  },



  beforeUpdate() {
      
      // data数据被修改之后,重新渲染到页面之前

  },

  



  updated() {
      
      // data数据修改之后,重新渲染到页面之后this.str="after"

  },

  beforeDestroy() {
      
      },

  destroyed() {
      
      },

</script>

</body>

</html>

Vue的组件复用

script中

<script>
// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
    
    
  data: function () {
    
    
    return {
    
    
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {
    
    { count }} times.</button>'
})
</script>

注意组件复用的data必须是一个函数

body中

<div id="components-demo">
  <button-counter></button-counter>
</div>

new Vue中

new Vue({
    
     el: '#components-demo' })

组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。

在Body中加上复用的地方

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<script src="js/vue.min.js"></script>

<body>
<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>
</body>

猜你喜欢

转载自blog.csdn.net/houzhicongone/article/details/121877218