0

Vue 新手——在探索中学习。

我正在尝试使用自定义对象作为 v-for 情况的数据源。到目前为止,还不行——我承认我不确定如何在 Vue 组件中按名称访问数据。

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");

可能未直接连接到数据提供者的自定义对象是 roomBuilder。

然后,在我想引用这个对象的组件中,我有这个代码:

<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>

这两个 POJO 是:

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;

房间.js

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

export default Room;

谢谢,对我放轻松。我通常是服务器端的人!我显然接线有误...尝试过

v-for="这个房间。$data.roomBuilder.getRooms()"

v-for="roomBuilder.getRooms() 中的房间"

等等

显然有一些我不明白的魔法正在发生!

谢谢!

4

0 回答 0