1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > vue实现组件间通信的几种方式(父传子 子传父)

vue实现组件间通信的几种方式(父传子 子传父)

时间:2020-03-01 15:32:30

相关推荐

vue实现组件间通信的几种方式(父传子 子传父)

提示:前端查漏补缺,仅代表个人观点,不接受任何批评

文章目录

一、vue组件之间的通信方式1.props (父传子)2. $emit (子传父)总结

一、vue组件之间的通信方式

1.props (父传子)

(1)创建子组件

在子组件通过props进行接收,注意子组件必须与父组件接收的对象名一致,当前例子为“id”,可以在组件中this.的方式使用props里面的值。

<template><div class="children"><div><div>我是子页面</div><div>{{id}}</div></div></div></template><script>export default {name:"Children",props:{id:{type:String, //类型判断default:'' //默认值}}}</script>

(2)父组件引入子组件

在父组件中通过:id向子组件通信。

<template><div class="parent-box"><div><div>我是父页面</div><div>{{id}}</div></div><children :id="toChildren"></children></div></template><script>import Children from './Children.vue' // 引入子组件export default {name:"Parent",components:{Children},data(){return {id:'我是父页面的内容',toChildren:'0001'}}}</script>

2. $emit (子传父)

(1)创建子组件,在子组件中通过this.$emit()方法向父组件通信,如下,点击触发事件,执行this.$emit(‘fromChildMethod’),触发父组件的fromChildMethod方法。

代码如下(示例):

<template><div class="children-box"><div><div>我是子页面</div><div>{{message}}</div><div><span @click="toParentMethod">点击触发父页面事件</span></div></div></div></template><script>export default {name:"Children",props:{message:{type:String,default:''}},methods:{toParentMethod(){this.$emit('fromChildMethod')}}}</script>

(2)在父组件的子组件上绑定fromChildMethod方法,对该方法进行监听,当该方法触发时,执行父组件中相应的方法fromChild。

<template><div class="parent-box"><div><div>我是父页面</div><div style="font-size:12px;">{{message}}</div><div style="font-size:12px;color:red">{{fromChildMsg}}</div></div><children :message="toChildrenMsg" @fromChildMethod="fromChild"></children></div></template><script>import Children from './Children.vue'export default {name:"Parent",components:{Children},data(){return {message:'我是父页面的内容',toChildrenMsg:'从父页面传过到子页面的内容',fromChildMsg:''}},methods:{fromChild(){this.fromChildMsg = '子页面触发的方法' //监听到子组件触发的方法,显示该内容}}}</script>

总结

Vue实现组件间通信的方式有很多种,除了上面两种常用的组件通信方式外,还有以下三种方式,具体用哪种方式应该视场景而定。

Vuex状态管理库(请点击访问讲解Vuex的文章)Router

可以通过动态路由、路由跳转方式进行传值,如this.$router.push({path:'xxx',query:{value:'xxx'}}),在跳转的时候顺便传值,通过this.$route.params.valuethis.$route.query.value获取到传过来的参数。该方式有局限性,只能在相互跳转的组件通信取值,且直接在跳转之后的页面进行刷新取不到值,视情况而用。缓存(sessionStoragelocalStoragecookie)

在同一个窗口不关闭的情况下,该窗口下的其他组件都可以取到缓存中已经存好的值,利用sessionStorage.setItem(key,value)、localStorage.setItem(key,value)等将值存起来,其他组件可以通过sessionStorage.getItem(key)、localStorage.getItem(key)等方式拿到,多个页面共享缓存数据,刷新页面数据不会销毁,可以用sessionStorage.removeItem(key)、localStorage.removeItem(key)的方式将缓存移除。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。