Vue组件之间的调用方法/传值
1.子组件调用父组件的方法(或父组件给子组件传值)
可简单理解为子组件使用父组件的方法或传递过来的值(简称子用)
(1)、在子组件中通过this.$parent.方法/属性 (获取父组件所有的方法和值)
(2)、将父组件的方法传递给子组件
(3)、通过props获取父组件的值
1.父组件调用子组件的时候动态绑定属性
<parent :dataList='dataList'></parent>
2.子组件定义props接收动态绑定的属性props: ['dataList']
3.子组件使用数据
2.父组件调用子组件的方法(或子组件给父组件传值)
父组件使用子组件的值或方法(简称父用)
(1)、使用$emit方法
1.子组件调用this.$emit('子方法名‘,传值)
2.父组件通过子组件绑定的'子方法名'获取传值父方法名。
<com2 @子方法名="值或父方法名"></com2>
(2)、使用ref属性
1.父组件调用子组件时绑定ref
<child ref='绑定名'></child>
2.在父组件中使用this.$refs.绑定名.属性/this.$refs.绑定名.方法
注意:ref 绑定在元素上时,返回元素节点对象
1.在元素上绑定ref
<span ref="myspan" class="redmy">23232</span>
2.在js中通过 this.$refs["myspan"] 使用
this.$refs["myspan"] 指代对象 // <span class="redmy">23232</span>
this.$refs["myspan"].className // redmy
3.非父子组件之间调用的方法或传值
Vue事件总线:this.$bus.$emit与this.$bus.$on
(bus实现)
1.创建Vue实例 // main.js
Vue.prototype.$bus = new Vue()
2.发射事件 // GoodsList
this.$bus.$emit('aaa')
3.监听事件 // home.vue
this.$bus.$on('aaa',()=>{
this.$refs.scroll.scroll.refresh()
})
4.示例:监听图片加载
//GoodsListItem.vue
<template>
<img :src="showImage" alt="" @load="imgLoad" />
</template>
imgLoad() {
if (this.$route.path.indexOf("/home") !== -1) {
this.$bus.$emit("homeImgLoad");
} else if (this.$route.path.indexOf("/detail") !== -1) {
this.$bus.$emit("detailImgLoad");
}
}
//home.vue
mounted() {
const refresh = debounce(this.$refs.scroll.refresh, 50);
this.$bus.$on("homeImgLoad", () => {
refresh();
});
}
//detail.vue
mounted() {
const refresh = debounce(this.$refs.scroll.refresh, 50);
this.$bus.$on("detailImgLoad", () => refresh());
}