组件
Vue中,组件是可复用的UI 片段,封装特定的功能或者相同样式的UI。功能相对单一,易于修改。
创建一个子组件SubA.vue:
<template>
<div class="content">
<p style="color: white">我是子组件</p>
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
.content{
width: 100pt;
height: 100pt;
background-color: blue;
}
</style>
在父组件中引入并使用:
<script setup lang="ts">
import SubA from './SubA.vue'
</script>
<template>
<SubA></SubA>
</template>
全局注册组件 app.component('SubA',SubA)
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import HelloWorld from './components/HelloWorld.vue'
import SubA from './components/SubA.vue'
const app = createApp(App);
app.component('HelloWorld',HelloWorld)
app.component('SubA',SubA)
app.mount('#app')
局部注册组件-在父组件中引入使用 import SubA from './SubA.vue'
父子组件之间传值
父传子
基本思想
- 父组件中给子组件绑定属性
- 子组件内部通过props选项接收数据
子传父
基本思想
- 父组件中给子组件标签通过@绑定事件
- 子组件内部通过 emit 方法触发事件
动态组件
有些场景会需要在两个组件间来回切换,比如 Tab 界面
vue 中使用 <component> 元素和特殊的 is attribute 实现的
<component :is="tabs[currentTab]" class="tab"></component>
示例: Home.vue
<template>
<div style="background-color: red;">
<p>子组件-----Home</p>
</div>
</template>
<script setup lang="ts">
</script>
Mine.vue
<template>
<div style="background-color: bisque;">
<p>子组件-----Mine</p>
</div>
</template>
<script setup lang="ts">
</script>
父组件:
<template>
<div class="screen">
<button v-for="(item, index) in tabs" :key="index" @click="current=index" :class="['tab_button', {active:current===index}]">
{{ item.name }}
</button>
<component :is="tabs[current].module" class="tab_content">
</component>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Home from './Home.vue'
import Mine from './Mine.vue'
const current = ref(0)
const tabs = [
{name:'Home', module:Home},
{name:'Mine', module:Mine}
]
</script>
<style scoped>
.screen {
width: 100%;
border: 1px solid #ccc;
padding: 10px 20px;
}
.tab_button {
width: 100px;
height: 40px;
border: 1px solid #ccc;
background-color: #ccc;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
margin-right: -1px;
}
.tab_button :hover {
background-color: red;
}
.tab_button.active {
background-color: aqua;
}
.tab_content {
padding: 5px;
height: 200px;
}
</style>