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>
- 子组件
Child.vue
定义props
用来接收父组件的数据
<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>
子组件->父组件
子组件到父组件的数据传递,主要是通过事件传递
- 子组件中定义相关的事件,传递一个图片的url传递给父组件,并显示,通过
$emit
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();
- 组件1
EmitterComponent.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>
- 组件2
ListenComponent.vue
接收数据
<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
},
网友评论