2
votes

I'm building a tree view using VueJS and I want to save the last clicked item in a store then use this store to show the last clicked item in a component.

I use a computed property in the the component where I want to show the item. The problem is that when the store changes it doesn't affect the computed property in the component.

The relative code is shown in this link: https://jsfiddle.net/eywraw8t/527884/

Vue.component('category-list', {
    template: `
    <div>
  <b>{{selectedCat}}</b>
  <ul>
        <category v-for='(catg, catgIdx) in categories' :category='catg' :key='catgIdx'
                            v-on:category-selected='categorySelected'/>
    </ul>
  </div>
  `,
    props: {
        categories: { type: Array, default: () => [] }
    },
  computed:{
  selectedCat(){
    return bookmarksStore.state.selectedCategory
  }
}
})
1

1 Answers

2
votes

You don't have dependency on reactive data (data,props) on your computed. So, when bookmarksStore change, your computed property is not triggered.

I would suggest to use Vuex in your case to create your store.

Using Vuex

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

const store = new Vuex.Store({
    state:{
      selectedCategory: {name: ""}
  },
  getters: {
    getselectedCategory: state => {
        return state.selectedCategory;
    }
  },
  mutations:{
    selectCategory(state, payload) {
        state.selectedCategory.name = payload
    }
  }
})

new Vue({
  el: "#app",
  store,
  data: {
...

Then, you could use this.$store.commit('selectCategory', category) to update the selectedCategory of your store and your computed property would look like

computed:{
  selectedCat(){
    return this.$store.getters.getselectedCategory
  }
}

Without Vuex

If you don't want to use Vuex, pass your bookmarksStore in your Vue root instance data.

new Vue({
  el: "#app",
  data: {
    bookmarksStore: new BookmarksStore(),
    ...

You can now pass the bookmarksStore to the child components using props and update it using events passed to the Vue root instance. This way, the bookmarksStore being a props in each child component, the computed property will be triggered.