T
T
TuMko2020-08-03 11:46:45
Vue.js
TuMko, 2020-08-03 11:46:45

How to pass variable value from state to Vue component variable?

Hello. There is a Users component:

export default {
  name: 'Users',
  data: () => ({
    showMoreBtn: false
  }),
  async mounted () {
    this.showMoreBtn = this.$store.state.showMore
    console.log(this.$store.state.showMore)
  }
}

And there is a store module:
export default {
  state: {
    userList: [],
    nextUrl: null,
    showMore: false
  },
  mutations: {
    createUserList (state, users) {
      state.nextUrl = users.links.next_url
      if (state.nextUrl !== null) {
        state.showMore = true
      } else {
        state.showMore = false
      }
      console.log(state.showMore)
    }
  },
  actions: {
    async fetchUsers ({ commit }) {
      const userList = await fetch('httsp://some-url').then(response => response.json())

      commit('createUserList', userList)
    }
  },
  getters: {
    getUserList: state => {
      return state.userList
    }
  }
}


The showMore (show more button) variable from state changes its value based on whether there is a link to the next page (state.nextUrl variable).
How can I pass the value of the state.showMore variable to the showMoreBtn component variable? In my version, undefined arrives instead of true/false. In the state itself, the showMore variable changes its value correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-08-03
@TuMko

showMoreBtn must be a computed property on the component. Something in the spirit

showMoreBtn() {
  return this.$store.state.showMore
}

Or use mapState

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question