程序员准则:思考一小时,撸码十分钟。
**1.在使用自定义组件时,首先要在父组件中将子组件需要的数据导入:**
<search
:searchList="searchList"
:selectValue="selectValue"
:selectFunc="selectfunc">
</search>
:selectList="selectList"就是我们需要导入的数据。
**2.在子组件中我们接收和使用:**
props:{
searchList:Array,
selectValue:Object
},
mounted() {
this.data = this.searchList
}
这里我们用props接收数据,props中的键值对是对数据的数据类型进行规定,使用者只能传输指定类型的数据,否则就报错。
而props中的数据,我们可以直接在当前组件中通过this.searchList来使用。props传过来的数据只作展示使用,如需修改,在data中写一个变量承接数据再处理
**3.子组件改变父组件的值(emit的使用)**
//子组件
this.$emit('selectFunc',value)
将父组件中的方法注入到子组件@selectFunc="selectFunc",然后在子组件中通过$emit调用它,并传递参数。达到修改目的。
//父组件
<search
@selectFunc="selectFunc"
:searchList="searchList"
:selectValue="selectValue">
</search>
selectFunc(value){
this.selectValue2 = value
console.log(this.selectValue)
console.log(this.selectValue2)
}
注:本文借鉴学习他人的,请移步:https://www.cnblogs.com/pengfei-nie/p/9134367.html