Search code examples
vue.jsstatevuex

How to get state item via props in vuejs with vuex


I'm sorry for my bad english. I've fromSelected props in vue. I want to get state selected item via props value.

I've from component.

<template>
    <h1>this.$store.state.fromSelected</h1>
</template>
<script>
    export default {
       props: ['fromSelected']
    }
</script>

in vuex state like this

const state = {
   'one': null,
}

I use my from component in root component like this

<from from-selected="one"></from>

When I use this.$store.state.fromSelected I want to get this.$store.state.one in from component.


Solution

  • It seems that the problem you are facing has to do with the flow of the data in Vue and Vuex. There are two different problems that need to be addressed here:

    Problem nr. 1 - Data Flow and Scopes:

    In your template code: <h1>this.$store.state.fromSelected</h1> you are trying to access the component property in the Vuex state. It will not exist there as it only exists in the components local scope. Here is an illustration of how the flow of data would work:

    enter image description here

    Problem nr. 2 - Static and Dynamic Props:

    In the line <from from-selected="one"></from> you are not prepending the property with a colon and therefore the prop will be considered a string literal and not an expression where you could pass in a variable. Read more here: https://v2.vuejs.org/v2/guide/components-props.html#Static-and-Dynamic-Props

    Solution:

    The solution would be to pass in the value from the Vuex state as a dynamic property to the component; like this:

    // Javascript
    const store = new Vuex.Store({
      state: {
        one: "This comes from the Vuex state"
      },
    })
    
    new Vue({
      el: "#app",
      store: store,
      components: {
        from: {
          template: '<span>{{ fromSelected }}</span>',
          props: ['fromSelected']
        }
      }
    })
    
    // Template
    <div id="app">
      <from :from-selected="$store.state.one"></from>
    </div>
    

    Try it here: https://jsfiddle.net/vngrcu5v/