vuejs / core

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
https://vuejs.org/
MIT License
47.66k stars 8.33k forks source link

reusable `<template>` in single file component #7897

Closed yunyuyuan closed 1 year ago

yunyuyuan commented 1 year ago

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

tobychidi commented 1 year ago

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

yunyuyuan commented 1 year ago

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

hminghe commented 1 year ago

https://github.com/vuejs/core/discussions/6898 join discussions

yunyuyuan commented 1 year ago

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

liulinboyi commented 1 year ago

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()],
})