2023-06-19

How to read parent attributes in Vue3 typescript

In the child component I am trying to write, I need to get the parent object. The commented out lines don't work.

AccordionState is:

export type AccordionKeys = | "open" | "disabled";

export type AccordionState = {
    [key: string]: {[key in AccordionKeys]: boolean; };
}

The child code is:

<script lang="ts">
    import { AccordionState } from "@/types/global";
    import { defineComponent, useAttrs } from "vue";

    export default defineComponent({
      name: "AccordionPane",
      props: {
        panelName: {
          type: String,
          required: true,
        },
      },
      computed: {
        open(): boolean {
          // const attrs = useAttrs();
          // const state = attrs.state as AccordionState;
          // return state[this.panelName].open && !state[this.panelName].disabled;
          return true;
        },
    disabled(): boolean {
      // const attrs = useAttrs();
      // const state = attrs.state as AccordionState;
      // return state[this.panelName].disabled;

      return false;
    },

The parent component. The computed getProps here shows that I am defining prop.state correctly, but the commented code in the AccordionPane does not work. the variable "state" is null. I don't see a lot of typescript examples online, and the javascript examples are so unstructured I don't know how to adapt them to typescript.

  <template>
    <div class="accordionControl">
      <slot ref="content"></slot>
    </div>
    <textarea class="debug" v-model="getProps"></textarea>
  </template>

  <script lang="ts">

  import { type AccordionState } from '@/types/global';
  import { defineComponent, type PropType } from 'vue';

  export default defineComponent({
    name: "AccordionControl",
    props: {
      state: {
        type: Object as PropType<AccordionState>,
        required: true,
      },
      isVert: {
        type: Boolean,
        default: false,
      },
      allOpen: {
        type: Boolean,
        default: false,
      }
    },
    computed: {
      getProps(): string {
        return JSON.stringify(this.$props, null, '  ');
      }
    }
  });
  </script>

The following link is one of the javascript examples and it works.

https://play.vuejs.org/#eNp1kDFrwzAQhf/K9RY5YGTaMbUL2ToWOnSoOtjxORhkSUhyl5D/3pMVXCcQ0KDHvfse9854cE7+zoR7rMPRjy5CoDi7N2XGyVkf4QyeBrjA4O0Egq1CGWWO1oQIUzhBk+aFeCetLXy1oc/Pet0/id2K+dRjTz5TFMoq6xSt8DUR6yrnczKLSJPTbSRWAPV1uWsUviiEfcufZ/7k6ZXFoq7WPSzxPyJdtyFKKW+8S+Kj63saRkMf3rpQwhzoEKMPd31oiuCSg9vY+Itv0YmfHZ+XDO2y2KyMgstJNVpNUttTsQBkV2ajbHm86QQvf3ztlVg=



No comments:

Post a Comment