P
P
Peter Sergeev2022-01-23 16:47:41
typescript
Peter Sergeev, 2022-01-23 16:47:41

How to make friends vue 3 options API on typescript with vue-router?

Hello.
The problem is that ts swears at $route
the error sounds like
Property '$route' does not exist on type '{ layout(): any; }'.
screenshot
61ed5b66830b7854339052.png

where the error appears

<template>
  <div id="app">
    <component :is="layout">
      <router-view/>
    </component>
  </div>
</template>

<script lang="ts">
import EmptyLayout from '@/layout/EmptyLayout.vue'
import MainLayout from '@/layout/MainLayout.vue'

export default {
  computed: {
    layout():any {
      return (this.$route.meta.layout || 'empty') + '-layout'
    }
  },
  components: {
    EmptyLayout,
    MainLayout
  }
}
</script>


router file
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: {
      layout: 'empty' as string
    }
  },
  {
    path: '/categories',
    name: 'categories',
    component: () => import('../views/Categories.vue'),
    meta: {
      layout: 'main' as string
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router


If you use the composition API, then everything is OK:
<template>
  <div id="app">
    <component :is="layout">
      <router-view/>
    </component>
  </div>
</template>

<script lang="ts">
import EmptyLayout from '@/layout/EmptyLayout.vue'
import MainLayout from '@/layout/MainLayout.vue'
import { computed } from 'vue'
import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    return {
      layout: computed(() => (route.meta.layout || 'empty') + '-layout')
    }
  },
  components: {
    EmptyLayout,
    MainLayout
  }
}
</script>


But just wondering how to use $route in the options API. Is there really no solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-01-23
@223606322

export default defineComponent({ ... })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question