vue组件传值:从基础到进阶

前言

当我们使用 vue 开发时,组件是最基础和重要的概念之一。而组件之间的数据传递也是我们在开发过程中必须面对的问题之一。vue 提供了多种方式来实现组件之间的数据传递,比如 propsemitparentchildren 等等。但是不同的方式适用于不同的场景,我们需要根据实际需求选择最合适的方式来完成组件之间的数据传递。在本文中,我们将会详细介绍 vue 中组件传值的各种方法,并且结合实例代码来帮助大家更好地理解和应用。


实现思路

父子传值: 在父组件中给子组件标签上绑定一个属性, 属性上挂载需要传递的值,在子组件通过 props:['自定义属性名'] 来接收数据。

子父传值: 在子组件中自定义一个事件,调用这个事件后,子组件通过 this.$emit('自定义事件名',要传递的数据) 发送父组件可以监听的数据,最后父组件监听子组件事件,调用事件并接收传递过来的数据。

兄弟传值: 在第一个组件中使用 $bus 传递自定义方法或者参数,然后在另一个同级组件中通过 $on 接收传过来的方法和参数。


话不多说,下面进入实战


父子传值

本篇小实例主要是模拟父组件向子组件传递数据的情况。

  • 父组件 index.vue
<template>
  <!-- 父组件 -->
  <div>
    <Child :message="informtion"></Child>
  </div>
</template>

<script>
// 引入子组件
import Child from "./subassembly/seed.vue";
export default {
  data() {
    return {
      informtion: "传递给子组件的数据", //要传递给子组件的数据
    };
  },
  //一定要注册组件
  components: {
    Child,
  },
};
</script>
  • 子组件 seed.vue
<template>
  <!-- 子组件 -->
  <h2>我是子组件<br />接收父组件值:{{ value }}</h2>
</template>

<script>
export default {
  data() {
    return {
      value: "",//接收的值
    };
  },
  props: {
    // message用于接收
    message: {
      type: String, //验证类型,也可以验证其他类型
      default: "", //如果父组件传值,则用父组件的值渲染,反之使用默认值
    },
  },
  watch: {
    message: {
      handler(newName, oldName) {
        this.value = newName;
      },
      deep: true, //深度监听
      immediate: true, //首次绑定的时候,是否执行 handler
    },
  },
};
</script>

实现效果
在这里插入图片描述


子父传值

本篇小实例主要是模拟子组件向父组件传递数据的情况。

  • seed.vue 子组件
<template>
  <!-- 子组件 -->
  <button @click="seedOnclick">我是子组件的按钮</button>
</template>

<script>
export default {
  data() {
    return {
      seedCode: "Romantic never die!", //子传父要传递的值
    };
  },
  methods: {
    // 子组件事件方法
    seedOnclick() {
      this.$emit("seed", this.seedCode); //参数1:自定义事件  参数2:要传递的值
    },
  },
};
</script>
  • index.vue 父组件
<template>
  <!-- 父组件 -->
  <div>
    <Child @seed="seedAccept"></Child>
  </div>
</template>

<script>
// 引入子组件
import Child from "./subassembly/seed.vue";
export default {
  //一定要注册组件
  components: {
    Child,
  },
  methods: {
    seedAccept(data) {
      console.log(data, "子组件传给父组件的值");
    },
  },
};
</script>

实现效果

在这里插入图片描述


父组件如何调用子组件的方法?

1. $refs方法

在父组件中,通过 ref 直接调用子组件的方法。

  • 父组件
<template>
  <!-- 父组件 -->
  <div>
    <button @click="clickOn">我是父组件的按钮</button>
    <Child ref="child"></Child>
  </div>
</template>

<script>
import Child from "./subassembly/seed.vue";
export default {
  data() {
    return {};
  },
  components: {
    Child,
  },
  methods: {
    clickOn() {
      this.$refs.child.wayOn();
    },
  },
};
</script>
  • 子组件
<template>
  <!-- 子组件 -->
  <div>
    {{num}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    wayOn() {
      this.num += 5;
      console.log("父组件调用");
    },
  },
};
</script>

在这里插入图片描述


2. emit、on方法

在父组件中,通过组件的 $emit$on 方法来调用。

  • 父组件
<template>
  <!-- 父组件 -->
  <div>
    <button @click="clickOn">我是父组件的按钮</button>
    <Child ref="child"></Child>
  </div>
</template>

<script>
import Child from "./subassembly/seed.vue";
export default {
  data() {
    return {};
  },
  components: {
    Child,
  },
  methods: {
    clickOn() {
      this.$refs.child.$emit("wayOn") 
    },
  },
};
</script>

  • 子组件
<template>
  <!-- 子组件 -->
  <div>
    {{num}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$on("wayOn", () => {
        this.num += 5;
        console.log("父组件调用");
      });
    });
  },
};
</script>

在这里插入图片描述


子组件如何调用父组件的方法?

1. $parent方法

$parent 方法是直接在子组件中通过 this.$parent.event 调用父组件的方法,如下:

  • 父组件
<template>
  <div>
    <!-- 子组件标签 -->
    <child></child>
  </div>
</template>
<script>
import child from "./dialog/dialog"; //引入子组件
export default {
  components: {
    // 注册组件
    child,
  },
  methods: {
    //父组件方法
    parentMethod() {
      console.log("子组件点击后触发此方法");
    },
  },
};
</script>
  • 子组件
<template>
  <div>
    <button @click="childOnclick()">子组件点击事件</button>
  </div>
</template>
<script>
export default {
  methods: {
    // 子组件点击事件
    childOnclick() {
      // 通过$parent方法调用父组件方法
      this.$parent.parentMethod();
    },
  },
};
</script>

在这里插入图片描述

2. $emit方法

$emit 方法是在子组件里用 $emit 向父组件触发一个事件,父组件监听这个事件即可,如下:

  • 父组件
<template>
  <div>
    <!-- 子组件标签 -->
    <child @fatherMethod="parentMethod"></child>
  </div>
</template>
<script>
import child from "./dialog/dialog"; //引入子组件
export default {
  components: {
    // 注册组件
    child,
  },
  methods: {
    //父组件方法
    parentMethod() {
      console.log("子组件点击后触发此方法");
    },
  },
};
</script>

  • 子组件
<template>
  <div>
    <button @click="childOnclick()">子组件点击事件</button>
  </div>
</template>
<script>
export default {
  methods: {
    // 子组件点击事件
    childOnclick() {
      // 通过$emit方法调用父组件方法
      this.$emit("fatherMethod");
    },
  },
};
</script>

在这里插入图片描述

3. 将方法传入子组件中

简单来说就是在父组件把方法传入子组件内,然后再在子组件中调用这个方法,如下:

  • 父组件
<template>
  <div>
    <!-- fatherMethod 传递的方法-->
    <child :fatherMethod="parentMethod"></child>
  </div>
</template>
<script>
import child from "./dialog/dialog"; //引入子组件
export default {
  components: {
    // 注册组件
    child,
  },
  methods: {
    //父组件方法
    parentMethod() {
      console.log("子组件点击后触发此方法");
    },
  },
};
</script>

  • 子组件
<template>
  <div>
    <button @click="childOnclick()">子组件点击事件</button>
  </div>
</template>
<script>
export default {
  props: {
    fatherMethod: {
      type: Function, //验证类型,也可以验证其他类型
      default: null, //如果父组件传值,则用父组件的值渲染,反之使用默认值
    },
  },
  methods: {
    // 子组件点击事件
    childOnclick() {
      if (this.fatherMethod) {
        this.fatherMethod();
      }
    },
  },
};
</script>

在这里插入图片描述


兄弟传值

本篇小实例主要是模拟同级组件间传递数据及调用方法的情况。

1. 全局注册

1.1 安装

npm install --save vue-bus
cnpm install --save vue-bus

1.2 引入并注册

// main.js
import VueBus from 'vue-bus'
Vue.use(VueBus)

1.3 使用

  • seed.vue 子组件1
<template>
  <div>
    <h3>子组件1</h3>
    <el-button type="primary" size="mini" @click="firstly">点击传值</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "子组件1定义的变量",
    };
  },

  methods: {
    firstly() {
      // 传了一个自定义方法 getTargetPointBUS 和参数 this.message
      this.$bus.$emit("getTargetPointBUS", this.message);
    },
  },
};
</script>

  • sons.vue 子组件2
<template>
  <div>
    <h3>子组件2<br />接收子组件1的值:{{ message }}</h3>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "",
    };
  },
  mounted() {
    // 触发自定义方法 getTargetPointBUS,同时触发自身的方法 getTargetPoint
    this.$bus.on("getTargetPointBUS", (data) => {
      console.log(data, "子组件1传的值");
      this.message = data;
      this.getTargetPoint(data);
    });
  },
  //组件销毁接触事件绑定
  destroyed: function () {
    this.$bus.off("getTargetPointBUS");
  },
  methods: {
    // 触发方法
    getTargetPoint(data) {
      console.log("触发子组件2方法");
    },
  },
};
</script>
  • index.vue 父组件
<template>
  <!-- 父组件 -->
  <div>
    <Child></Child>
    <Electronic></Electronic>
  </div>
</template>

<script>
// 引入子组件
import Child from "./subassembly/seed.vue";
import Electronic from "./subassembly/sons.vue";
export default {
  //一定要注册组件
  components: {
    Child,
    Electronic,
  },
};
</script>

2. 局部注册

2.1 新建一个 eventBus.js 文件

import Vue from 'vue'
const eventBus = new Vue()
export default eventBus

2.2 在使用的组件中引入

import eventBus from "../eventBus";

2.3 使用

  • seed.vue 子组件1
<template>
  <div>
    <h3>子组件1</h3>
    <el-button type="primary" size="mini" @click="firstly">点击传值</el-button>
  </div>
</template>

<script>
import eventBus from "../eventBus";
export default {
  data() {
    return {
      message: "子组件1定义的变量",
    };
  },

  methods: {
    firstly() {
      // 传了一个自定义方法 getTargetPointBUS 和参数 this.message
      eventBus.$emit("getTargetPointBUS", this.message);
    },
  },
};
</script>
  • sons.vue 子组件2
<template>
  <div>
    <h3>子组件2<br />接收子组件1的值:{{ message }}</h3>
  </div>
</template>

<script>
import eventBus from "../eventBus";
export default {
  data() {
    return {
      message: "",
    };
  },
  mounted() {
  	// 触发自定义方法 getTargetPointBUS,同时触发自身的方法 getTargetPoint
    eventBus.$on("getTargetPointBUS", (data) => {
      console.log(data, "子组件1传的值");
      this.message = data;
      this.getTargetPoint(data);
    });
  },
  //组件销毁接触事件绑定
  destroyed: function () {
    eventBus.$off("getTargetPointBUS");
  },
  methods: {
    // 触发方法
    getTargetPoint(data) {
      console.log("触发子组件2方法");
    },
  },
};
</script>
  • index.vue 父组件
<template>
  <!-- 父组件 -->
  <div>
    <Child></Child>
    <Electronic></Electronic>
  </div>
</template>

<script>
// 引入子组件
import Child from "./subassembly/seed.vue";
import Electronic from "./subassembly/sons.vue";
export default {
  //一定要注册组件
  components: {
    Child,
    Electronic,
  },
};
</script>

实现效果
在这里插入图片描述


相关推荐

从原理到实战:vue中的provide/inject让你的代码更优美

  • 11
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水星记_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值