二、Vue.js 组件

组件的使用:

  1. 建立组件
  2. 引入组件
  3. 挂载组件
  4. 在模板中使用

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>
相关文章
相关标签/搜索