Subscribe on changes!

reusable `<template>` in single file component

avatar
Mar 15th 2023

What problem does this feature solve?

like this:

<script setup>
const isMobile = useIsMobile();
const menuItems = [
  {name: 'Item-1', url: '/item1'},
  {name: 'Item-2', url: '/item2'},
  {name: 'Item-3', url: '/item3'},
]
</script>

<template>
  <div>
    <div v-if="!isMobile">
      <container :outlet="menu"/>
    </div>
    <My-Dropdown v-else>
      <template #dropdown-content>
        <container :outlet="menu"/>
      </template>
    </My-Dropdown>
  </div>
</template>

<template #menu>
  <ul>
    <li v-for="item in menuItems">
      <router-link to="item.url">{{ item.name }}</router-link>
    </li>
  </ul>
</template>

What does the proposed API look like?

<template>
  <div>
    <container :outlet="xxx"/>
  </div>
</template>
<template #xxx>
</template>

That is better than make the #menu as a new .vue file, and define some emit and props to communicate

avatar
Mar 16th 2023

Moi React dev switching to Vue😏. I think this feature could be useful and make Vue more robust. I have wanted to do this before. There is one current solution. Use JSX or Function components (h stuff) in the script

avatar
Mar 16th 2023

@tobychidi Not React, it’s Angular,TSX does not work well with nuxtjs in my tests

avatar
Mar 17th 2023

@hminghe wow,心有灵犀属于是。closed because duplicate

avatar
Mar 19th 2023

I have wite a simple plugin to reuse template.

npm i unplugin-vue-reuse-template -D
// vite.config.ts
import vueReuseTemplate from 'unplugin-vue-reuse-template/vite'
import Vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [Vue(), vueReuseTemplate()],
})