vue中各种通信传值方式总结

2020-06-14 06:14:47易采站长站整理

}
}
</script>
<style scoped>

</style>

About代码:


<template>
<div id="about">
<p>我是关于页:{{ message }}</p><button type="button" @click="handleChange">回到首页</button>
</div>

</template>

<script>

export default {
name: 'About',
data () {
return {
message: ""
}
},
mounted(){
this.message = sessionStorage.getItem("text") //读取缓存
},
updated(){

},
methods:{
handleChange(){
this.$router.push({ path: "/" })
}
}
}
</script>
<style scoped>

</style>

3、父组件向子组件通信

定义父组件Head,还是用上面的例子,父组件传递一句话给子组件,如果传递的参数很多,可使用json数组{}的形式。

例子: Head父组件代码


<template>
<div id="head">
<About :text=message></About> //将message参数传给子组件
</div>

</template>

<script>
import About from '@/components/About.vue'
export default {
name: 'Head',
components:{
About
},
data () {
return {
message : "我是阿格斯之盾"
}
},
mounted(){

},
methods:{

}
}
</script>
<style scoped>

</style>

About子组件代码


<template>
<div id="about">
<p>我是关于页:{{ text }}</p>
</div>
</template>

<script>

export default {
name: 'About',
props:{
'text':[] //子组件接受数据,[]里面可以写传入类型,如果不符合会报错
},
data () {
return {
message: ""
}
},
mounted(){

},
updated(){

},
methods:{
handleChange(){

}
}
}
</script>
<style scoped>

</style>

4、子组件向父组件通信 子组件向父组件通信是通过emit事件发送的,话不多说,直接上案例,还是利用上面的案例稍作修改 About子组件代码:


<template>
<div id="about">
<button @click="handleChange">点击发送消息给父组件</button>
</div>
</template>

<script>

export default {
name: 'About',
props:{
'text':[] },
data () {
return {
message: ""
}
},
mounted(){

},
updated(){

},
methods:{
handleChange(){
this.$emit( "child-message" , "我是阿格斯之盾" ) //提交信息