点击父组件改变某个值,将这个值传入子组件,子组件通过props接收,用watch来检测这个值的变化来触发某个方法。这样做比较方便很容易理解,但是watch监听有缺陷,比如我监听一个对象,里面某个value值变化,我发现watch并没有监听到,目前还在看是什么问题,
例 父组件:
<template><div @click="setShare(item)"></div>
<normal :shareItem="shareItem">
</normal>
<script>
@import share from './share.vue'
methods: {
setShare(item){
this.shareItem = item
}
}
</script>
</template>
子组件:
<template>
props: {
shareItem: {
type: Object,
default: null
}
watch: {
shareItem (val) {}
}
}
</template>
第二种方法是直接触发子组件的方法,利用ref获取,这种方式也有缺陷主要是ref的缺陷,不能实时更新dom,不能在渲染过程获取这个dom,只能在渲染完成后才能获取,一般跟nextTick一起用
例父组件
<div @click="setShare(item)"></div>
<normal ref="shareDom">
</normal>
<script>
@import share from './share.vue'
methods: {
setShare(item){
this.$refs.shareDom.text(item)
}
}
</script>
</template>
子组件:
<template>
methods: {
text(val) {}
}
</template>
第一种用watch监听简单直接,但是watch有缺陷,第二种没有watch缺陷但是ref有缺陷,根据具体情况来定
第三种方法是可以通过eventBus来触发,在src第一层目录下建立一个新的文件名字叫eventBus
例:import vue from 'vue'
const eventBus = new vue
export {eventBus}
然后在你需要的文件中去调用vue中的$emit()触发某个事件的方法,$on监听某个事件的方法,
父组件
例: import {eventBus} from '../eventBus.vue'
reset () {
eventBus.$emit('listen')
}
子组件
例:import {eventBus} from '../../eventBus.vue'
mounted() {
eventBus.$on('listen', ()=> {
this.drop=false
})
}