0

Parent component have method

layoutMain.vue

<script lang="ts">
....
hideRightSidebar() {
    document.body.classList.remove('right-bar-enabled')
}
....
</script>

<template>
    <div id="wrapper">
     ....
    </div>
       <Rightbar />
    </div>
</template>

in child component "Rightbar" i want call parent method

if not use typescript i just call

<script>
export default {
    name: "RightBar"
    ....
    methods: {
       handleRightBarClick(e, el) {
           this.$parent.hideRightSidebar()
       },

and all work, but if I add TS lang

<script lang="ts">
import { Vue } from 'vue-property-decorator'

export default class RightBar extends Vue {

handleRightBarClick(e: any, el: any) {
    (this.$parent as any).hideRightSidebar()
}
....

i have error

TypeError: Cannot read property '$parent' of undefined

how fix that?

I also have a question about accessing the i18n plugin

in nuxt.config.js i have a setting:

nuxt.config.js

....
i18n: {
    locales: ["en", "fr", "es", "ar"],
    defaultLocale: "en",
    vueI18n: {
    fallbackLocale: "en",
        messages: {
            en: require("./locales/en.json"),
            fr: require("./locales/fr.json")
        }
    }
}
....

it works fine, if I don't use TS

<script>
export default {
    data() {
        return {
            ....
            current_language: this.$i18n.locale
        };
    },
    ....

but if I use TS, I have error

current_language: this.$i18n(<-- error HERE).locale

Property '$i18n' does not exist on type 'Readonly<Record<never, any>> & Vue'

how fix that?

  • Does this answer your question? [Call parent method with component](https://stackoverflow.com/questions/46208610/call-parent-method-with-component) – Matt U May 23 '21 at 17:43
  • I'm not sure if I can call the correct $emit using TS on my own, because I get an error { Cannot read property '$emit' of undefined }, because I have not yet learned how to properly call $emit in TS – Ярослав Прохоров May 23 '21 at 17:51
  • Emitting an event from the child, and handling it in the parent, is generally better practice than communicating directly from child -> parent, as Vue's approach is one-way data flow. It prevents children from erroneously mutating the parent's state. I recommend learning how to emit events. – Matt U May 23 '21 at 18:22
  • @MattU I know about this, the problem is that I want to translate the project to Typescript, but I don’t know how to do this using the TS syntax – Ярослав Прохоров May 23 '21 at 18:33
  • I understand. Learn how to do it in TS. – Matt U May 23 '21 at 18:33

0 Answers0