Vue2父传子、子传父和兄弟间互传

首先创建局部组件来完成之间的传值。

一、父组件给子组件传值

父类组件: 使用props属性,父组件向子组件传递数据。

<template>
  <div id="app">
    <div>
      <son-boy :obj="obj" :arr="arr"></son-boy>
    </div>
  </div>
</template>

<script>
import SonBoy from "./components/SonBoy.vue";
export default {
  name: "App",
  data() {
    return {
      obj: {name: "张三",age: 22,sex: "男"},
      arr: [1, 2, 3, 4, 5],
    };
  },
  components: {
    SonBoy,
  },
};
</script>
<style></style>

子类组件:

<template><!-- 父传子 -->
  <div>
    <h2>{
   
   { obj }}</h2>
    <h2>{
   
   {arr}}</h2>
  </div>
</template>
<script>
export default {
  name: "SonBoy",
  props: {
    obj:{
        type:Object
    },
    arr:{
        type:Array
    }
  },
};
</script>
<style scoped></style>

二、父组件给子组件传值

子类组件:子组件向父组件传值,使用自定义事件$emit

在子组件中定义一个方法使用$emit,'itemclick'是事件名,item是传过去的值。

<template> <!-- 子传父 -->
  <div>
    <button
      v-for="(item, index) in categoties"
      @click="hand(item)"
      :key="index"
    >{
   
   {item.name}}</button>
  </div>
</template>
<script>
export default {
  name: "SonBoder",
  data() {
    return {
      categoties: [
        {id: "aaa",name: "热门推荐"},
        {id: "bbb",name: "手机数码"},
        {id: "ccc",name: "家用家电"},
        {id: "ddd",name: "电脑办公"},
      ],
    };
  },
  methods: {
    hand(item) {
      this.$emit('ageItem',item)
    },
  },
};
</script>
<style scoped></style>

父类组类:

<template>
  <div id="app">
    <div>
      <son-boder @ageItem="hanger"></son-boder>
    </div>
  </div>
</template>
<script>
import SonBoder from "./components/SonBoder.vue";
export default {
  name: "App",
  data() {
    return {
    };
  },
  methods: {
    hanger(item) {
      console.log(item.name);
    },
  },
  components: {
    SonBoder,
  },
};
</script>

<style>
</style>

 

三、子组件之间互传

兄弟之间传值需要借组bus传递。

新建bus.js用来传递中间的媒介。

import Vue from 'vue';
export default new Vue;

创建兄弟1:

<template>  <!-- 父传子 -->
  <div>
    <button @click="goWork" >传送</button>
  </div>
</template>
<script>
import bus from '@/common/bus'
export default {
  name: "SonBoy",
data(){
    return{
        msg:'我是兄弟'
    }
},
methods: {
    goWork(){
        bus.$emit('SonBoder',this.msg);
       }
   },
};
</script>
<style scoped></style>

创建另一个兄弟用来接收数据:

扫描二维码关注公众号,回复: 14773829 查看本文章
 <template> <!-- 子传父 -->
  <div>
    {
   
   {str}}
  </div>
</template>
<script>
import bus from "@/common/bus";
export default {
  name: "SonBoder",
  data() {
    return {
      str: "",
    };
  },
  mounted() {
    bus.$on("SonBoder",(data) => {
      this.str = data;
    });
  },
};
</script>
<style scoped></style>

 

猜你喜欢

转载自blog.csdn.net/qq_65715980/article/details/126236635