Vue组件之间的数据传递方式(带例子)

1.父传子:prop传递数据

父组件

<template>
  <div>
    <h2>parent</h2>
    <p>msg:{{ msg }}</p>
    <hr />
    <ceng1 :msg="msg"></ceng1>
  </div>
</template>
<script>
import ceng1 from "./ceng1.vue";
export default {
  data() {
    return {
      msg: "父组件数据",
    };
  },
  components: {
    ceng1,
  },
};
</script>

 子组件

<template>
  <div>
    <h1>层1</h1>
    <p>获取父组件数据:{{ msg }}</p>
    <hr />
    <ceng2></ceng2>
  </div>
</template>
<script>
import ceng2 from "./ceng2.vue";
export default {
  components: {
    ceng2,
  },
  props: ["msg"],
};
</script>

2.子传父:自定义事件 this.$emit

//子组件
 <button @click="send">向父组件发送数据</button>
...
<script>
export default {
  data(){
    return{
      son:"儿子"
    }
  },
  methods:{
    send(){
      this.$emit('sendData',this.son)
    }
  }
};
</script>
//父组件
<ceng1  @sendData="sendData"></ceng1>
...
<script>
import ceng1 from "./ceng1.vue";
export default {
  data() {
    return {
      msg: "父组件数据",
    };
  },
  methods:{
    sendData(val){
      console.log('子组件数据',val);
    }
  },
  components: {
    ceng1,
  },
};
</script>

3.父组件实例:$parent

//子组件调用
this.$parent.msg

4.子组件实例:$children

//父组件调用子组件数据
this.$children[0].son

5.dom元素和子组件实例:$refs

//父组件
<ceng1 :msg="msg" @sendData="sendData" ref="ceng1"></ceng1>
...
<script>
 getDom(){
      console.log(this.$refs.ceng1.son);
    }
</script>

6.获取根组件:$root

7.深层传递:provide/inject(跨组件)

//爷爷组件
<script>
export default {
...
  //深层传递数据
  provide(){
    return {
      info:'这是一条信息',
      msg:'哈哈哈'
    }
  }
};
</script>
//孙子组件
<template>
  <div>
    <h1>层3</h1>
    <p>----获取爷爷组件数据----</p>
    <p>{{info}}</p>
    <p>{{msg}}</p>
  </div>
</template>

<script>
export default {
  //接受数据
  inject:['msg','info']

}
</script>

8.原型链数据:Vue.prototype.xx=xx

9.本地存储:localStorage.setItem()/getItem()

10.eventBus 中央系统-跨组件之间传递数据

11.Vuex

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值