父子组件
父组建向子组件传值
通过自定义事件接收事件;子组件通过props接收数据
<template>
<div id="app">
// 父组件 传递数据给 子组件
<MyInput :list="list" />
</div>
</template>
子组件向父组件传值
子组件通过$emit 向父组件传递自定义事件
<template>
<div id="app">
// 父组件 接收子组件传递的注册事件
<MyInput @addItem="addItem" />
</div>
</template>
父组件
<template>
<div id="app">
<MyInput :list="list" @addItem="addItem" />
</div>
</template>
<script>
import MyInput from "./views/Input.vue";
export default {
components: { MyInput },
data() {
return {
list: [
{ name: "one", title: "one" },
{ name: "two", title: "two" },
{ name: "three", title: "three" },
],
};
},
methods: {
addItem(value) {
console.log("我是子组件传递过来的输入值" + value);
},
},
};
</script>
<style lang="less">
</style>
子组件
<template>
<div class="input">
<input type="text" v-model="inputValue" />
<button @click="add">添加</button>
<ul>
<li v-for="(item, index) in list" :key="index">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
name: "Input",
data() {
return { inputValue: "" };
},
props: {
// 接收父组件传递的数据
list: Array,
},
methods: {
add() {
// 注册事件 传递给父组件
this.$emit("addItem", this.inputValue);
},
},
};
</script>
兄弟组件
创建一个eventBus.js文件
import Vue from "vue"
const eventBus = new Vue()
export default eventBus
<template>
<div id="app">
// 两个兄弟组件
<MyInput :list="list" @addItem="addItem" />
<ShowInput />
</div>
</template>
MyInput
eventBus.$emit("showInput", this.inputValue)
<template>
<div class="input">
<input type="text" v-model="inputValue" />
<button @click="add">添加</button>
</div>
</template>
<script>
import eventBus from "../utils/eventBus";
export default {
name: "Input",
data() {
return { inputValue: "" };
},
methods: {
add() {
eventBus.$emit("showInput", this.inputValue);
},
},
};
</script>
ShowInput
eventBus.$on("showInput", this.handleValue)
<template>
<div class="showInput"></div>
</template>
<script>
import eventBus from "../utils/eventBus";
export default {
methods: {
handleValue(title) {
console.log("title", title);
},
},
mounted() {
eventBus.$on("showInput", this.handleValue);
},
};
</script>