Using custom model objects as provider for v-for in Vue?

575 views Asked by At

new to Vue - learning as I go about exploring.

I'm trying to use a custom object as data source for a v-for situation. So far, not working - I admit I'm not sure how to access data by name in a Vue component.

main.js

import Vue from "vue";

import App from "./App.vue";
import router from "./router";
import store from "./store";
import VueKonva from "vue-konva";
Vue.use(VueKonva);

import RoomBuilder from "@/model/RoomBuilder";

Vue.config.productionTip = false;

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

The custom object, which may not be wired right into the data provider, is roomBuilder.

Then, in the component where I want to reference this object, I have this code:

<template>
  <v-stage ref="stage" :config="stageSize">
    <v-layer>
      <v-rect ref="background" :config="backgroundConfig"></v-rect>
      <v-rect
        v-for="room in roomBuilder.getRooms()"
        :key="room.id"
        :config="room.config"
      ></v-rect>
    </v-layer>
  </v-stage>
</template>

<script>
export default {
  name: "RoomGrid",
  data() {
    return {
      stageSize: {
        width: 1000,
        height: 1000
      },
      backgroundConfig: {
        width: 50,
        height: 50,
        fill: "#2B2B2B"
      }
    };
  },
  mounted() {
    this.$nextTick(function() {
      window.addEventListener("resize", this.fitStageIntoParentContainer);
      this.fitStageIntoParentContainer();
    });
  },
  methods: {
    fitStageIntoParentContainer() {
      const parentElement = this.$parent.$el;
      const background = this.$refs.background.getNode();
      background
        .setAttr("width", parentElement.clientWidth)
        .setAttr("height", parentElement.clientHeight);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss"></style>

The two POJOs are:

RoomBuilder.js

import Room from "@/model/Room";

class RoomBuilder {
  construct() {
    this.rooms = [new Room(1)];
  }

  drawOnto(konvaStage) {
    console.log(konvaStage);
  }

  getRooms() {
    return this.rooms;
  }
}

export default RoomBuilder;

and

Room.js

class Room {
  construct(id) {
    this.id = id;
    this.config = {
      x: 10,
      y: 10,
      fill: "white",
      width: 10,
      height: 10
    };
  }
}

export default Room;

Thanks, and go easy on me. I'm typically a server-side guy! I clearly have wired something wrong... have tried

v-for="room in this.$data.roomBuilder.getRooms()"

v-for="room in roomBuilder.getRooms()"

etc.

Clearly there's some magic afoot I don't understand!

Thank you!

0

There are 0 answers