1、通过prop传递
prop不仅可以传递属性值,同样也可以传递函数作为回调函数使用,以达到子传父的效果
1)、父组件Home.vue
//父组件
//此处我们把基本数据类型:string,饮用数据类型Object,以及函数Function同时传递给子组件
<template>
<div>
<div>我是爹组件</div>
<div>父testString: {{ testString }}</div>
<div>父testObject: {{ testObject.name }}</div>
<BedRoom
:testString="testString"
:testObject="testObject"
:onChange="handleChange"
></BedRoom>
</div>
</template>
<script>
import BedRoom from './bedRoom'
export default {
name: 'HomePage',
components: {
BedRoom,
},
data() {
return {
testString: '我是爹组件传过来的字符串',
testObject: {
name: '我是爹组件传过来的对象',
},
}
},
methods: {
goto(pathName) {
this.$router.push({ name: pathName })
},
handleChange(stringData, objectData) {
this.testString = stringData
this.testObject = objectData
console.log('data', this.testString, this.testObject)
},
},
}
</script>
<style lang="less" scoped></style>
2)、子组件
//子组件
//此处我们采用prop的方式接收传递过来的数据以及函数等
<template>
<div>
<div>我是子组件</div>
<div>testString: {{ testString }}</div>
<div>testObject: {{ testObject.name }}</div>
<div>
<div>
<button
@click="
handleForceChange('直接修改字符串', {
name: '直接修改对象',
})
"
>
子组件中强行修改prop传过来的数据
</button>
</div>
<button
@click="
handleChange('我是子组件传过来的字符串', {
name: '我是子组件传过来的对象',
})
"
>
点击我改变父组件的数据
</button>
</div>
</div>
</template>
<script>
export default {
name: 'BedRoom',
props: {
testString: {
type: String,
required: false,
},
testObject: {
type: Object,
required: false,
},
onChange: {
type: Function,
required: false,
},
},
data() {
return {}
},
methods: {
handleChange(stringData, objectData) {
this.onChange(stringData, objectData)
},
handleForceChange(stringData, objectData) {
// this.testString = stringData
// this.testObject.name = objectData.name
console.log('data', stringData, objectData)
},
},
}
</script>
<style lang="less" scoped></style>
启动运行后,可以看到页面显示为:
因为prop为单向数据流传递,所以在子组件中并不能直接修改父组件里的数据值,所以点击第一个按钮之后并不会发生任何改变,(代码中注释掉是因为放开之后会报错,单向数据里不支持修改)
但是点击第二个按钮,因为是回调父组件里的方法,所以此处是可以修改成功,显示为下图
2、通过$emit(),ref
父组件中:
//父组件,我们在原来的代码上修改一下组件内容
<BedRoom
ref="bedRoomRef"
@handleChange="handleChange"
:testString="testString"
:testObject="testObject"
:onChange="handleChange"
></BedRoom>
//methods中添加函数
handelGetSon() {
const sendData = this.$refs.bedRoomRef.handleSendData()
this.testString = sendData.testString
this.testObject.name = sendData.testObject.name
},
子组件:
//添加按钮
<button @click="handleEmit">通过$EMIT触发父组件传递的函数</button>
//methods中添加函数
handleEmit() {
this.$emit('handleChange', '我是子组件Emit传过来的字符串', {
name: '我是子组件Emit传过来的对象',
})
},
handleSendData() {
return {
testString: '我是子组件传过来的字符串',
testObject: {
name: '我是子组件传过来的对象',
},
}
},
此时的页面为:
然后我们点击emit这个按钮:
然后我们再点击最后这个,通过父组件里的按钮来获取子组件里的数据:
同时也可以通过localStorage这种方式
3、通过localStorage
使用后需要通过localStorage.removeItem()给创建的缓存清除掉;例:
//父组件中需要传递给子组件的数据获取到的时候装入localStorage
//此处例子中以mounted中举例
mounted(){
localStorage.setItem('test', 'test')
},
//子组件中在需要使用的地方通过localStorage.getItem获取即可
mounted(){
localStorage.getItem('test')
},
//需要注意,一般使用完毕最好给缓存清除掉
localStorage.removeItem('test')