9. Vue Components and Life Cycle Functions

Keywords: Vue Attribute

I. Component Creation and Use

1. Create Components

Create a Home.vue component under the src/components folder. The html part of the component needs to be surrounded by the < template> root node. At the same time, the component style and component functions can be set:

<template>
    <!-- All content should be included by the root node. -->
    
    <div>
    
        <h2>This is a home page component ---- {{msg}}</h2>
    
        <button @click="run">Click to run</button>
    
    </div>
</template>

<script>
export default {
    data() {
        return {
            msg: 'I am a component'
        }
    },
    methods: {
        run() {
            alert(this.msg);
        }
    }
}
</script>

<style lang="scss">
    h2 {
        color: red;
    }
</style>

Note: All the objects introduced into the component, while introducing the style and function of the component, will also take effect!!!

If you want the style in a component to only work in that component, there are two ways:
_The first way to set id is:

<template>
    <!-- All content should be included by the root node. -->
    
    <div id="home">
    
        <h2>This is a home page component ---- {{msg}}</h2>
    
        <button @click="run">Click to run</button>
    
    </div>
</template>

<script>
.......
</script>

<style lang="scss">
// Let h2-style objects only work in this component (otherwise, all objects that introduce this component will apply h2-style)
#home {
    h2 {
        color: red;
    }
}
</style>

__The second way to set the scoped attribute of scss is:

<style lang="scss" scoped>
// Let h2-style objects only work in this component (otherwise, all objects that introduce this component will apply h2-style)
h2 {
    color: red;
}
</style>
2. Introducing and mounting components
<script>
	// 1. Introducing Components
	import Home from './components/Home.vue';
	export default {
    name: 'app',
    data() {
        return {
            todo: '',
            list: []
        }
    },
    components: {
        // 2. Mount Components
        "v-home": Home
    }
}
</script>

Posted by glennn3 on Thu, 28 Mar 2019 03:00:33 -0700