动态组件 在 App 文件里面存放的 data 数据 ,拿出来通过 子文件 home.vue 中{{ message }}
来 使用 类似于父传子,子传父 通信那一块的内容
其中有用到 props传递数据
在home组件,设置home组件的内容
其他组件有其他组件的内容, 如 default 的默认值
App.vue
data() {
return{
tabs:["home","about","category"],
// currentIndex:0
currentTab:"home"//初始
}
},
home.vue
<script>
export default {
props:{//传递数据
name:{
type: String,
default: " "
},
age:{
type: Number,
default:0
}
},
}
</script>
完整代码:
APP.vue
<template>
<div class="app">
<div class="tabs">
<template v-for="(item) in tabs" :key="item">
<button :class="{active: currentTab===item}"
@click="itemClick(item)"><!--点击使名字等于tabs里的内容-->
{{ item }} <!--item即tab-->
</button>
</template>
</div>
<div class="view">
<!--v-if 显示组件-->
<!-- <template v-if="currentIndex===0">
<home></home>
</template>
<template v-if="currentIndex===1">
<about></about>
</template>
<template v-if="currentIndex===2">
<category></category>
</template> -->
<!--第二种:动态组件-->
<!-- is 中的组件需要来自,局部注册的组件或者全局注册的组件 -->
<!-- 定义数字变量 -->
<!-- <component :is ="tabs[currentIndex]"></component> -->
<!-- <component :is ="currentTab"></component> -->
<component name="why" :age="18" :is ="currentTab"></component><!--定义名字为变量-->
</div>
</div>
</template>
<script>
import Home from './vues/Home.vue'
import About from './vues/About.vue'
import Category from './vues/Category.vue'
export default {
components:{
Home,
About,
Category,
},
data() {
return{
tabs:["home","about","category"],
// currentIndex:0
currentTab:"home"//初始
}
},
methods:{
itemClick(tab){
this.currentTab= tab
}
}
}
</script>
<style scoped>
.active{
color:red
}
</style>
home.vue
<template>
<h2>home :{{ name }} - {{ age }}</h2>
</template>
<script>
export default {
props:{//传递数据
name:{
type: String,
default: " "
},
age:{
type: Number,
default:0
}
},
}
</script>
<style>
</style>