typescript 内部html中包含列表定义的Vue3组件

vlju58qv  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(168)

我想创建上下文菜单。由于上下文菜单的性质取决于使用位置,条目会有所不同。因此,我尝试创建一个Vue.js 3组件,允许在其innerHtml中定义列表,而不是将列表作为属性传递。
我想到的一个示例用法应类似于以下示例:

<!-- when using in a list of articles -->
<contextMenu>
    <item name="copy" @click="copyMethod"/>
    <item name="delete" @click="deleteMethod"/>
</contextMenu>

<!-- in a list of users -->
<contextMenu>
    <item name="edit user" @click="editMethod"/>
    <item name="delete user" @click="deleteMethod"/>
</contextMenu>

据我所知,slots不是我的问题的解决方案,因为它们似乎是相反的。
像这样的东西但没有名单作为财产

const ContextMenu = {
  template:
  `<div>
    <span v-for="entry in entries" :key="entry.name">
        <router-link :to="entry.to" >
            <v-button>{{ entry.name }}</v-button>
        </router-link>
    </span>
</div>`   
}
w6lpcovy

w6lpcovy1#

我认为slots正是您在这种情况下所需要的。

const { createApp, ref } = Vue;

const vButton = { 
  props: ['name'],
  template: `<button type="button" :name="name"><slot></slot></button>` 
}

const ContextMenuItem = {
  components: { vButton },
  props: ['entry'],
  template: `<router-link :to="entry.to"><v-button>{{ entry.name }}</v-button></router-link>`   
}

const ContextMenu = { 
 components: { ContextMenuItem },
  template: `<div><slot></slot></div>`
}

const App = {
  components: {
    vButton, ContextMenuItem, ContextMenu
  },
  methods: {
    copyMethod() { console.log('copyMethod()')},
    editMethod() { console.log('editMethod()')},
    deleteMethod() { console.log('deleteMethod()')},
  }
}

const app = createApp(App)
app.mount('#app')
<div id="app">  
    <!-- when using in a list of articles -->
    <context-menu>
        <context-menu-item :entry="{ name: 'copy'}" @click="copyMethod"></context-menu-item>&nbsp;
        <context-menu-item :entry="{ name: 'delete'}" @click="deleteMethod"></context-menu-item>
    </context-menu>
    <br />
    <!-- in a list of users -->
    <context-menu>
        <context-menu-item :entry="{ name: 'edit-user'}" @click="editMethod"></context-menu-item>&nbsp;
        <context-menu-item :entry="{ name: 'delete-user'}" @click="deleteMethod"></context-menu-item>
    </context-menu>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

相关问题