Vue 组件数据传递

2020-02-27  本文已影响0人  CoderMiner

Vue 组件数据传递

父组件->子组件

父组件到子组件的数据通过 props 传递

父组件 App.vue , 传递父组件中的数据 <Child :todos="items" />

<template>
  <div id="app">
    <img :src="url" />
    <Child :todos="items" />
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  name: "App",
  components: {
    Child,
  },
  data() {
    return {
      items: [
        {
          id: 1,
          title: "kevin"
        },
        {
          id: 2,
          title: "john"
        }
      ],
      
    };
  }
};
</script>
<template>
  <div>
    <ul>
      <li v-for="(item, index) in todos" :key="index">{{ item.title }}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "Child",
  props: ["todos"],
  data() {
    return {};
  }
};
</script>

子组件->父组件

子组件到父组件的数据传递,主要是通过事件传递

Child.vue

<button @click="emittClick">Click</button>
  methods: {
    emittClick() {
      this.$emit("replace-img", "https://vuejs.org/images/logo.png");
    }
  }

App.vue

<img :src="url" />
<Child :todos="items" v-on:replace-img='onChangeImg'/>
  methods: {
    onChangeImg(url) {
      this.url = url;
    }
  }

兄弟组件之间传递数据

通过 bus 传递数据

Events.js

import Vue from 'vue'

export const EventBus = new Vue();
<template>
  <button @click="clickMe()">Click Me</button>
</template>
<script>
import { EventBus } from "../Events";

export default {
  data() {
    return {
      count: 0
    };
  },

  methods: {
    clickMe() {
      this.count += 1;
      EventBus.$emit("emittedEvent", this.count);
    }
  }
};
</script>

<template>
  <div>The Counter is : {{ value }}</div>
</template>
<script>
import { EventBus } from "../Events";

export default {
  data() {
    return {
      value: 0
    };
  },
  mounted() {
    EventBus.$on("emittedEvent", data => {
      this.value = data;
    });
  }
};
</script>

App.vue

template

    <EmitterComponent />
    <ListenComponent />

script

  components: {
    EmitterComponent,
    ListenComponent
  },

使用 vuex 进行数据管理,单独介绍 vuex 的使用方法 待续...

上一篇下一篇

猜你喜欢

热点阅读