组件 创建,注册,挂载
2025年5月7日小于 1 分钟
组件 创建,注册,挂载
提示
1scoped(样式需要scoped声明以免污染全局)
2必须有div根元素包裹
创建组件
在相应分层目录创建组件
示例如下:
src/components/home/v_home.vue
<template>
<div class="home">
<div class="red">
<h2 >{{ title }}</h2>
</div>
</div>
</template>
<script>
export default {
name: 'v_home',
data() {
return {
title:"我是一个首页组件"
};
},
};
</script>
<style lang="css" scoped>
.red
{
background-color: red;
}
</style>
在父级或者根组件注册
2.1引入
import Home from "./components/home/v_home.vue";
2.2注册
components: {
// HelloWorld
'v-home':v_home,
},
2.3挂载
<v-home></v-home>
整体示例:
<template>
<div id="app">
<!-- 开始 -->
<!-- <router-view></router-view> -->
<!-- <img alt="Vue logo" src="./assets/logo.png"> -->
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<v-home></v-home>
<!-- 结束 -->
</div>
</template>
<script>
// import HelloWorld from './components/HelloWorld.vue'
import Home from "./components/home/v_home.vue";
export default {
name: 'app',
components: {
// HelloWorld
'v-home':v_home,
},
data()
{
return{
msg:"你好,vue",
isRed:true,
}
},
methods:
{
},
}
</script>
<style>
#app {
/* font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px; */
}
.red
{
background-color: red;
}
.blue
{
background-color: #1F20DFFF;
}
.size
{
width: 200px;
height: 200px;
}
</style>