父向子传值:
父组件通过属性绑定的方式进行传值,子组件通过props接收
子向父传值:
父组件通过事件绑定接收,子组件通过$emit传值
兄弟组件传值:
设置一个事件中心eventBus ,传递方通过$emit传值,接收方通过$on接收
想要进行组件传值,那当然是先要 “注册组件” 啦。
// 这里是全局注册组件 一般很少用 了解一下
在main.js文件中
import MenuPanel from "../components/menuPanel.vue";
Vue.component('menuPanel',MenuPanel)
在需要展示的页面 <menuPanel></menuPanel>
// 常用的 局部注册组件 来咯
以home.vue页面为例
import MenuPanel from "../components/menuPanel.vue";
与data()平级
components: {
MenuPanel: MenuPanel,
},
在页面<MenuPanel></MenuPanel>
父向子传值:
// 父页面:
<GetLonglat :msg-object="msg"></GetLonglat>
import GetLonglat from "../components/getLonglat.vue";
components: {
GetLonglat: GetLonglat
},
// 子页面
在页面使用传递过来的值时 记得加this
props: {
msgObject: Object, //这样可以指定传入的类型,如果类型不对,会警告
},
多种接收父组件传值的方式!!
//子组件通过props来接收数据:
//方式1:
props: ['msgVal']
//方式2 :
props: {
msgVal: Array //这样可以指定传入的类型,如果类型不对,会警告
}
//方式3:
props: {
msgVal: {
type: Array, //指定传入的类型
//type 也可以是一个自定义构造器函数,使用 instanceof 检测。
default: [0,0,0] //这样可以指定默认的值, 一把指定默认值为空
}
// 或者
msgVal: {
type: Array,
default:function(){
return:[0,0,0]
}
}
}
//注意 props 会在组件实例创建之前进行校验,所以在 default 或 validator 函数里,诸如 data、computed 或 methods 等实例属性还无法使用
子向父传值:
// 子页面
<div @click="childClick(item)"></div>
childClick(item) {
this.$emit("child-by-value", '传递的数据');
},
// 父页面
<MenuPanel @child-by-value="childByValue"></MenuPanel>
import MenuPanel from "../components/menuPanel.vue";
childByValue(val) {
console.log(val, '接收的数据')
},
兄弟组件传值:
在工具文件夹里新建一个event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
在所需要文件内引入
import { EventBus } from "../util/event-bus";
传递方
EventBus.$emit('send-by-bus', '传递的数据')
接收方
EventBus.$on("send-by-bus", (data) => {
console.log(data, '接收的数据')
});