首页 > 技术文章 > Vue2.0入门系列——组件和生命周期

sunnyyangwang 2019-01-17 10:04 原文

1、文件目录结构

Vue.js官网下载

Vue2.0组件定义,自行编写

2、编写文件

如下,

 

3、整体思路

定义子组件——注册组件——模板编写——引用模板——实例化

访问方式:直接访问html文件。

源代码:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>vue2.0组件属性</title>

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

         <script>

           var Home={//1、定义子组件

              template:'#aaa' //4、套用模板

           };

          

           Vue.component('home-test',Home); //2、注册组件

          

           window.onload=function(){

              new Vue({

                      el:'#box',

                          data:{

                             msg: 'welcome vue2.0'

                          }

                   });

           };

         </script>

</head>

<body>

    <template id="aaa">

         <!--3、template模板,下面只允许只有一个标签属性-->

            <div>

              <h3>我是第一个组件</h3>

                   <strong>加粗标签属性</strong>

            </div>

         </template>

         <div id="box">

            <!--5、子组件实例化,引用-->

            <home-test></home-test>

            {{ msg }}

         </div>

</body>

</html>

 

自此,组件属性介绍完成。

 

4、组件声明周期介绍

             beforeCreate  组件实例刚刚被创建,属性都没有

              created   实例已经创建完成,属性已经绑定

              beforeMount  模板编译之前

              mounted 模板编译之后

              beforeUpdate 组件更新之前

              updated  组件更新完毕

              beforeDestroy 组件销毁前

              destroyed       组件销毁后

 

5、源代码

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>vue2.0生命周期</title>

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

         <script>

           window.onload=function(){

              new Vue({

                      el:'#box',

                          data:{

                             msg: 'welcome vue2.0'

                          },

                          methods: {

                             update(){this.msg='数据已更新'},

                             destroy(){this.$destroy();}

                          },

                          beforeCreate(){console.log('组件实例刚刚被创建');},

                          created(){console.log('实例已经创建完成');},

                          beforeMount(){console.log('模板编译之前');},

                          mounted(){console.log('模板编译之后');},

                          beforeUpdate(){console.log('组件更新之前');},

                          updated(){console.log('组件更新之后');},

                          beforeDestroy(){console.log('组件销毁之前');},

                          destroyed(){console.log('组件销毁之后');}

                   });

           };

         </script>

</head>

<body>

         <div id="box">

            <input type="button" value="更新数据" @click="update">

            <input type="button" value="销毁数据" @click="destroy">

            {{ msg }}

         </div>

</body>

</html>

界面访问测试,查看console输出。

自此,vue生命周期介绍完毕。 

推荐阅读