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
},