davestewart / vuex-pathify

Vue / Vuex plugin providing a unified path syntax to Vuex stores
https://davestewart.github.io/vuex-pathify
MIT License
1.37k stars 57 forks source link

Map component helper to prop value #48

Closed ken-afh closed 5 years ago

ken-afh commented 5 years ago

I'm trying to create a single file component that receives as a prop the path of the store data item it needs to manipulate. To do this, I'm passing this.myProp to sync(path) as a computed property.

<template></template>
<script>
import { sync } from 'vuex-pathify'

export default {
props: myProp,
data() {
  return {
    ...
  },
},
computed: {
  myStoreValue: sync(this.myProp),
}

When I do this, I get:

Uncaught TypeError: Cannot read property 'myProp' of undefined

Which I interpret to mean that "this" isn't defined when the constructor is run. How can I accomplish what I'm trying to do?

davestewart commented 5 years ago

Hi Ken.

That's not going to work as at the time the component definition is declared, there is no this!

This is just a Vue thing, not a Pathify thing.

I can explain more if that's not clear.

davestewart commented 5 years ago

P.S. Congrats on your first issue!

ken-afh commented 5 years ago

Thanks, Dave! That's what I was afraid of. I appreciate you taking the time to confirm my suspicions - even if it wasn't what I wanted to hear!

davestewart commented 5 years ago

If you really do need to create a property dynamically, you can monkey-patch computed properties in beforeCreate():

There's some documentation on that:

Here's some code which does what you need:

I hope that helps!

davestewart commented 5 years ago

Actually, what do you know - you can use the registerModule() helper directly to do it!

It's been so long since I looked at the code of this project. Sorry :P

ken-afh commented 5 years ago

Cool! Thanks for taking the time to dig into the code to help me out. I will check out registerModule() to see how it works. BTW - thanks for vuex-pathify! I like the simplicity and consistency of using paths for access to the store.