9. Vue3.x中的單文件組件 定義組件 注冊組件 以及組件的使用


一、Vue3.x 中的組件

組件可以拓展html標簽,解決html標簽構建應用的不足,Vue項目由一個一個的組件組成。 image-20201029174738754.png

二、Vue3.x 中定義組件注冊組件

1、定義一個公共的頭部組件 components/header.vue

<template>
<header>我是一個頭部組件</header>
</template>

<script>
export default {

}
</script>

<style lang="scss" scoped>
// scoped表示css是一個局部作用域
header {
    width: 100%;
    height: 44px;
    text-align: center;
    line-height: 44px;
    background: #000;
    color: #fff;
}
</style>

2、定義一個公共的頭部組件 components/Home.vue

<template>
<v-header />
<h5>{{title}}</h5>
<button @click="getTitle()">獲取home組件里面的title</button>
</template>

<script>
import Header from './Header'
export default {
    data() {
        return {
            title: "首頁組件title"
        }
    },
    methods: {
        getTitle() {
            alert(this.title)
        }
    },
    components: {
        "v-header": Header
    }
}
</script>

<style lang="scss">
h5 {
    text-align: center;
}
</style>

2、定義一個公共的頭部組件 components/User.vue

<template>
<header>我是用戶組件的頭部</header>
<br>

<ul>
    <li v-for="(item,index) in list" :key="index">
        {{item}}
    </li>
</ul>
</template>

<script>
export default {
    data() {
        return {
            list: []
        }
    },
    mounted() {
        for (var i = 0; i < 10; i++) {
            this.list.push(`我是第${i}條數據`)
        }
    }
}
</script>

<style lang="scss">
ul {
    list-style: none;
}
</style>

2、引入自定義組件 、注冊組件、使用組件

<template>
<Home />
<br>
<hr>
<br>
<User />
</template>

<script>
//1、引入組件
import Home from './components/Home';
import User from './components/User';
export default {
    data() {
        return {
            msg: "app根組件",
        };
    },
    components: { //2、掛載組件
        Home,
        User
    }
};
</script>

<style lang="scss">
h2 {
    text-align: center;
}
</style>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM