Vue组件的传值方式
父组件传值给子组件
-
通过props传递
-
父组件:
<child :list = 'list' />
-
子组件:
props['list']
,接收数据,接受之后使用和data中定义数据使用方式一样
子组件传值给父组件
-
在父组件中给子组件绑定一个自定义的事件,子组件通过$emit()触发该事件并传值。
-
父组件:
<child @receive = 'getData' /> getData(value){value就是接收的值}
-
子组件:
this.$emit('receive',value)
兄弟组件之间传值
步骤
-
创建一个新的js文件,文件内容为暴露一个vue实例
// 暴露vue实例 import Vue from 'vue'; export default new Vue;
-
按需导入/全局导入
- 全局导入直接在main.js文件中进行导入
- 按需导入则在需要用到的文件中导入即可
import Bus from "../js/bus";
-
创建好子组件在父组件上显示
例如:在app.vue中写入<template> <div id="app"> <one></one> <two></two> </div> </template> <script> import one from "./views/one.vue"; import two from "./views/two.vue"; export default { name: "DemoOne", components: { one, two, }, }; </script> <style> </style>
-
子组件一:给子组件二发送数据
-
导入(如已经全局导入则不需要再次导入)
-
写一个方法通过调用导入的文件
Bus.$emit('自定义命名事件',数据)
发送数据sendData() { Bus.$emit("getdata", this.num); },
-
-
子组件二:接收子组件一发送的数据
-
导入(如已经全局导入则不需要再次导入)
-
在vue的created钩子函数中通过
Bus.$on('自定义命名事件',箭头函数)接收数据
Bus.$on("getdata", (num) => { this.aa = num; });
-
文件内容
- bus.js文件
// 暴露vue实例
import Vue from 'vue';
export default new Vue;
- 父组件
<template>
<div id="app">
<one></one>
<two></two>
</div>
</template>
<script>
import one from "./views/one.vue";
import two from "./views/two.vue";
export default {
name: "DemoOne",
components: {
one,
two,
},
};
</script>
<style>
</style>
- 子组件一
<template>
<div>
<h1>组件一</h1>
<button @click="sendData">点击发送数据</button>
</div>
</template>
<script>
import Bus from "../js/bus";
export default {
name: "DemoOne",
data() {
return {
num: 100,
};
},
mounted() {},
methods: {
sendData() {
Bus.$emit("getdata", this.num);
},
},
};
</script>
<style lang="scss" scoped>
</style>
- 子组件二
<template>
<div>
<h1>组件二{{ aa }}</h1>
</div>
</template>
<script>
import Bus from "../js/bus";
export default {
name: "DemoTwo",
data() {
return {
aa: 0,
};
},
created() {
Bus.$on("getdata", (num) => {
this.aa = num;
});
},
methods: {},
};
</script>
<style lang="scss" scoped>
</style>