Last active
June 27, 2020 09:39
-
-
Save prograhammer/94c4d54290de0c3db811e70dee1bbc09 to your computer and use it in GitHub Desktop.
Vue Provide Inject reactive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template lang="pug"> | |
li(@click='$store.commit("UPDATE_SIDE_NAV_ACTIVE_ITEM", $el)') | |
slot | |
</template> | |
<script> | |
export default { | |
data () { | |
return { | |
provideData: { | |
el: null | |
} | |
} | |
}, | |
mounted () { | |
this.provideData.el = this.$el | |
}, | |
// See Vue documentation at https://vuejs.org/v2/api/#provide-inject. | |
provide () { | |
const injectedData = {} | |
return { injectedData: this.makeReactive(injectedData, this.provideData) } | |
}, | |
methods: { | |
// Hooks a provider up with a reactive source, so the provider is reactive. | |
// See https://vuejs.org/v2/guide/reactivity.html#How-Changes-Are-Tracked. | |
makeReactive (target, source) { | |
const keys = Object.keys(source) | |
for (let i = 0; i < keys.length; i++) { | |
let prop = keys[i] | |
Object.defineProperty(target, prop, { | |
enumerable: true, | |
get: () => source[prop], | |
set: (val) => { source[prop] = val } | |
}) | |
} | |
return target | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment