Data
首先要注意的事情,在组件中,data必须是一个函数而不是一个对象
data(){
return{
}
}
组件的注册
- 组件名
组件名使用短横线分隔命名的时候,在引用这个组件的时候必须也采用短横线分隔的方式;
使用首字母大写命名的时候,引用时即可使用短横线分隔也可使用首字母大写;
**注意:**直接在 DOM (即非字符串的模板) 中使用时只有 kebab-case 是有效的。
- 全局注册
Vue.component('组件名',{
//...选项...
})
- 局部注册
new Vue({
el:'#app',
components:{
'component-a': ComponentA,
'component-b': ComponentB
}
})
- 模块系统
这是工作中最常用的组件注册方式
在vue项目中创建一个components目录,并将组件放置在对应的文件中
//首先导入你想要使用的组件
import ComponentA from 'components/componentA'
export default {
//将组件进行注册
components:{
ComponentA
}
}
Prop 父组件向子组件传值
首先我们要明白,Prop 实际上就是在组件上注册的一些自定义 attribute。
- Prop 的大小写
注意:浏览器会把所有大写的属性名转化成小写字符,所以prop名需要等价的短线分隔命名的方式 - Prop 类型
//--------这些类型都可以进行传递---------------
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise // or any other constructor
}
3.传值过程
父组件
<template>
<div>
//传递动态数据childreArr
<children-a :fruits-arr = 'childreArr'></children-a>
</div>
</template>
<script>
//组件引入
import ChildrenA from '../../components/Login/Children'
export default {
name:'login',
//组件注册
components:{
ChildrenA
},
data(){
return{
childreArr:['苹果','荔枝','草莓']
}
}
}
</script>
子组件
<template>
<div>
//html中直接使用即可
<div class="header-box" :key="index" v-for="(item,index) in fruitsArr">
{{item}}
</div>
</div>
</template>
<script>
export default {
name:'LoginHeader',
//子组件直接使用props进行接收
props:['fruitsArr'],
</script>
$emit子组件向父组件传值
//父组件
<template>
<div>
//自定义一个方法接收子组件传的值
<children-a @childerFn = 'parentFn'></children-a>
//直接使用子组件传递过来的值
<div>{{getChildrenVal}}</div>
</div>
</template>
<script>
//同样将子组件引入
import ChildrenA from '../../components/Login/Children'
export default {
name:'login',
//组件注册
components:{
ChildrenA
},
data(){
return{
getChildrenVal:''
}
},
methods:{
parentFn(val){
//此处的val就是子组件传递给父组件的值
this.getChildrenVal = val;
}
}
}
</script>
子组件
<template>
<div>
<button @click = 'giveParent'>传值给父组件</button>
</div>
</template>
<script>
export default {
name:'LoginHeader',
data(){
return{
msg:"我是子组件传递过来的值"
}
},
methods:{
giveParent(){
this.$emit('childerFn',this.msg)
}
}
}
</script>