Vue 組件數(shù)據(jù)傳遞

Vue 組件數(shù)據(jù)傳遞

父組件->子組件

父組件到子組件的數(shù)據(jù)通過 props 傳遞

  • 在父組件注冊子組件,傳遞數(shù)據(jù)到子組件

父組件 App.vue , 傳遞父組件中的數(shù)據(jù) <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>
  • 子組件 Child.vue 定義 props 用來接收父組件的數(shù)據(jù)
<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>

子組件->父組件

子組件到父組件的數(shù)據(jù)傳遞,主要是通過事件傳遞

  • 子組件中定義相關(guān)的事件,傳遞一個圖片的url傳遞給父組件,并顯示,通過 $emit

Child.vue

<button @click="emittClick">Click</button>
  methods: {
    emittClick() {
      this.$emit("replace-img", "https://vuejs.org/images/logo.png");
    }
  }
  • 父組件接收子組件的數(shù)據(jù)

App.vue

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

兄弟組件之間傳遞數(shù)據(jù)

通過 bus 傳遞數(shù)據(jù)

Events.js

import Vue from 'vue'

export const EventBus = new Vue();
  • 組件1 EmitterComponent.vue 發(fā)送數(shù)據(jù)
<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>

  • 組件2 ListenComponent.vue 接收數(shù)據(jù)
<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 進行數(shù)據(jù)管理,單獨介紹 vuex 的使用方法 待續(xù)...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容