最近使用了別人的一個插件,看到別人用了provid和inject,感覺很有意思,mark一下
具體的東西,注意事項可以看官方的文檔,我們只是討論一下,provide和inject的常規用法
首先我們知道,父子組件傳值的話,使用的是prop,但是要是爺孫組件傳值的話,用什麼?
有人講用bus或者用vuex的,這當然行,但是vue提供了另外一種針對於爺孫或者其他的直系傳值的方法,就是provide和inject。
注意,必須是直系的嵌套關係才能夠使用
//祖先組件裏面
<template>
<view>
<test></test>
</view>
</template>
<script>
import test from '../../components/test/test.vue'
export default {
data() {
return {
};
},
// provide 值接收一個對象
provide:{
foo:'123123'
},
components:{
test
}
}
</script>
<style lang="scss">
</style>
在祖先頁面中,我們定義了一個provide的對象,這個對象有一個屬性,屬性名就是我
在下面的直系親屬的組件裏面通過inject獲取到的
在這個頁面的孫子組件裏面 我我們通過inject[‘foo’]來獲取到父組件的值
<template>
<view>
{{testFoo}}
</view>
</template>
<script>
export default {
data() {
return {
testFoo: this.foo
};
},
inject: ['foo'],
mounted() {
console.log('beforeCreate', this)
}
}
</script>
<style lang="scss">
</style>
獲取到了這個值以後,我們就能夠使用它了
另外一個最長用的用法,大概就是刷新組件了
比如我們向刷新一個組件,或者在孫子或者更加後代的組件裏面去控制父組件裏面的元素的顯示和隱藏
//父親組件
<template>
<view>
<test></test>
<view v-if="ifHide">測試顯示可隱藏</view>
</view>
</template>
<script>
import test from '../../components/test/test.vue'
export default {
data() {
return {
data1:'123123',
ifHide:true
};
},
// provide 值接收一個對象
provide(){
return{
domHide:this.domHide
}
},
methods:{
domHide(){
let that = this
that.ifHide = !that.ifHide
}
},
components:{
test
}
}
</script>
<style lang="scss">
</style>
//孫子或者其他直系親屬裏面
<template>
<view>
<button @click="changeHide">點擊</button>
</view>
</template>
<script>
export default {
data() {
return {
testFoo: this.foo
};
},
inject: ['domHide'],
mounted() {
console.log('beforeCreate', this)
},
methods:{
changeHide(){
this.domHide()
}
}
}
</script>
<style lang="scss">
</style>