vue组件间传值

组件间传值:

  • 父传子通过props:
//子组件
<template>
 <div class="hello">
   <h1>子组件:{{title}}</h1>
 </div>
</template>
//定义一个props
components: {
   HelloWorld
 },
 props: ['title'],
// 父组件  传递数据
 <HelloWorld :title="newMsg"/>
  data(){
    return{
      newMsg:'父级data'
    }
  },
  • 子传父自定义事件:
// 子组件
data() {
    return {
        name:'hello',
        age:18
    }
  },
 methods: {
    submit() {
      this.$emit("sendEventToParent", this.name,this.age);
    }
  },
  //触发
   created() {
    this.submit()
  },
// 父组件
 <HelloWorld @sendEventToParent="doSomething" />
  data(){
    return{
      msg:'',
      msg2:''
    }
  },
  methods:{
    doSomething(name,age){
       this.msg = name
       this.msg2 = age
    }
  }
  • 访问子组件 ref:
//父组件
<HelloWorld ref="childcom" />

mounted(){
   console.log(this.$refs.childcom,'2222')
    console.log(this.$refs.childcom.age,'2222')
 }

在里插入图片描述

  • 组件通信之$bus
Vue.prototype.$bus = new Vue();
组件a
destroyed()() {
  this.$bus.$emit("handels",1)
  }
组件b
created() {
 this.$bus.$on("handels", (res) => {
    console.log(res);
  });
  }
  beforeDestroy() {
  // 在组件销毁之前清除自定义事件
  this.$bus.$off("handels");
 
},
注意事项,参考下列链接

链接:https://blog.csdn.net/u010007013/article/details/89515208

  • 缓存取值如localstorage
  • 另外 p a r e n t 、 parent、 parentchildren、$root,也可以访问父子组件的数据
  • vuex
  • 动态路由传值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值