vue 组件之间传值

vue组件之间传值

1、父传子(props)

(1)父组件

<template>
 <div class="father">
    <child :msg="data">child>    // 3.使用子组件
 div>
template>

<script>
import Child from "@/components/child.vue"; // 1.引入子组件

export default {
  name: "father",
  data() {
    return {
      data: "dataFromFather"
    };
  },
  components: {
    // 2.注册子组件
    Child
  }
};
script>

(2)子组件

<template>
 <div>
    <div>我是子组件:div>
    <div class="child">子组件接收到的内容:{{msg}}div>
 div>
template>

<script>
export default {
  name: "Child",
  props: {
    //用来接父组件传来的值
    msg: ""
  }
};
script>

2、子传父($emit)

(1)子组件

<template>
 <div>
     <button @click="setData">传值button>  // 1.触发事件setData
 div>
template>

<script>
export default {
  name: "Child",
  data() {
    return {
      data: "dataFromSon"
    };
  },
  methods: {
    setData() {
      this.$emit("passData", this.data); // 2.将值绑定到passData上传给父组件
    }
  }
};
script>

(2)父组件

<template>
 <div class="father">
    <div>父组件:div>
    <div>父组件接收到的内容:{{name}}div>
    <child @passData="changeData">child>  // 1.绑定自定义事件passData
 div>
template>

<script>
import Child from "@/components/child.vue";

export default {
  name: "father",
  data() {
    return {
      name: ""
    };
  },

  // 注册组件
  components: {
    Child
  },

  methods: {
    changeData(msg) {
      // 2.获取子组件传来的值msg
      this.name = msg;
    }
  }
};
script>

3、非父子(bus)

(1)bus.js

import Vue from 'vue'
export default new Vue()

(2)组件1

<template>
  <div class="component1">
    <div>我是组件1div>
    <button @click="changeData">点击button>  // 2.触发事件changeData
  div>
template>

<script>
import Bus from './bus.js'  // 1.引入bus.js

export default {
  name: 'component1',
  data() {
    return{
      msg: 'dataFromComponent1'
    }
  },
  methods: {
    changeData(){
      Bus.$emit('passData', this.msg) // 3.将值绑定到passData上传给组件2
    }
  },
}
script>

(3)组件2

<template>
    <div class="component2">
        <div>我是组件2div>
    div>
template>

<script>
import Bus from './bus.js'  // 1.引入bus.js

export default {
  name: 'component2',

  mounted() {
    Bus.$on('passData', (msg)=>{  // 2.接收组件1传来的值
        console.log(msg)
    })
  },

}
script>

你可能感兴趣的:(html,Vue,vue.js,javascript,前端)