0
votes

I am very new to Vue.js, so please be patient with me if the problem is too simple.

so I have the following code of Home.vue:

<template>
  <div class="home">
    <div>
      <b-table striped hover :items="borrowingHistroy"></b-table>
    </div>
  </div>
</template>

<script>
import userData from '@/data/user_data';

export default {
  name: 'Home',
  data() {
    return {
      userId: 0,
    };
  },
  computed: {
    borrowingHistroy: () => userData[this.userId].borrowingHistory,
  },
};
</script>

The code did not get rendered as I get the following error/warning:

[Vue warn]: Error in render: "TypeError: Cannot read property 'userId' of undefined"

if I change the borrowingHistry in the computed to the following then it works:

 borrowingHistroy: () => userData[0].borrowingHistory,

so that warning must mean this is not defined here?

But then how can I use the userId defined in "data"?

****** modified ******

The following are my other parts of code:

main.js:

import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';

import App from './App.vue';
import router from './router';
import store from './store';

Vue.use(BootstrapVue);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

App.vue:

<template>
<div id="app">
    <img alt="Vue logo" src="./assets/images/HPL.png">
  <div id="nav">
    <router-link to="/">Home</router-link>
  </div>
  <router-view />
</div>
</template>

router/index.js:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;

store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  },
});
2

2 Answers

1
votes

Or you could simplify the computed property definition using parenthesis, so you will keep the application's context:

 borrowingHistroy() {
   return userData[this.userId].borrowingHistory
 }
2
votes

You should pass the component instance as arrow function parameter :

  borrowingHistroy: (vm) => userData[vm.userId].borrowingHistory,

According to the official docs :

Note that if you use an arrow function with a computed property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument:

computed: {
  aDouble: vm => vm.a * 2
}