vue组件之间数据共享(一)

组件注册

局部注册组件

//组件调用
<div>
    <Left></Left>
</div>

//组件导入
import Left from '@/components/Left.vue'

//组件注册
export default{
    components:{
        Left    
    }
}

全局注册

在 vue 项目的 main.js 入口文件中,通过 Vue.component() 方法,可以注册全局组件。示例代码如下:

import Left from '@/components/Left.vue' 

//全局注册
//参数1:字符串格式,表示"组件名称"
//参数2:需要被全局注册的那个组件
Vue.component('MyLeft',Left)

// 组件调用
<my-left></my-left>

组件传参

父组件向子组件共享数据

props接收参数的几种方式:

 export default {
        // 第一种格式
        props: ['prams1'],
 
        // 第二种格式
        // props:{
        //     prams1: Number,
        // },

        // 第三种格式
        // props:{
        //     prams1: {
        //         type: Number,
        //         default: 100
        //     },
        // },

父组件源码

<template>
  <div>
    <son :msg="message" :user="userinfo"></son>
  </div>
</template>
 
<script>
import Son from './Son'
export default {
  components: {
    Son
  }, 
  data() {
    return {
        userinfo: "用户信息1212",
        message: "我的消息1212"
    };
  },
};
</script>

子组件源码

<template>
  <div>
    <h1>我是子组件</h1>
    <p>{{user}}</p>
    <p>{{msg}} </p> 
  </div>
</template>


<script>
export default { 
  props:["user","msg"],
  data() {
    return {};
  },
};
</script>

子组件向父组件共享数据

子组件向父组件共享数据使用自定义事件。示例代码如下

父组件Parent.vue源码:

<template>
  <div class="pp">
    <h1>父组件</h1>
    <h1 class="xs">{{ num }}</h1>
    <son @numchange="getNewCounter"></son>
  </div>
</template>
 
<script>
import Son from "./Son";
export default {
  components: {
    Son,
  },
  data() {
    return {
      num: 1,
    };
  },
  methods: {
    getNewCounter(val) {
      console.log("父组件得到的参数", val);
      this.num = val;
    },
  },
};
</script>

<style scoped>
.pp {
  background-color: rgb(255, 0, 0);
  border-color: black;
  padding: 30px;
}
.xs {
  height: 20px;
  width: 20px;
}
</style>

子组件Son.vue源码:

<template>
  <div class="ss">
    <button @click="add">子组件加1</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      count: 1,
    };
  },
  methods: {
    add() {
      this.count += 1;
      this.$emit("numchange", this.count);
      console.log("子组件", this.count);
    },
  },
};
</script>

<style scoped>
.ss {
  background-color: rgb(64, 140, 68);
  margin: 10px;
}
</style>

兄弟组件之间的数据共享

在 vue2.x 中,兄弟组件之间数据共享的方案是EventBus

 EventBus 的使用步骤
① 创建 eventBus.js 模块,并向外共享一个 Vue 的实例对象
② 在数据发送方,调用 bus.$emit('事件名称', 要发送的数据) 方法触发自定义事件
③ 在数据接收方,调用 bus.$on('事件名称', 事件处理函数) 方法注册一个自定义事件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值