我有一个菜单组件,简单地说,它接收一个带有一系列选项的props ,并 for each 选项呈现菜单中的一个项目.我希望能够根据用例定制每个菜单项中的标记,所以我在菜单项元素中使用了占位符.

你可以在这fiddle本书中看到一个例子.

const Menu = {
    template: `
        <ul>
            <li v-for="item in options" :class="item.colour">
            <slot></slot>
            <span class="label">{{item.name}}</span>
          </li>
        </ul>
    `,
    data: () => {
        return {
            options: [
                { name: 'one', colour: 'red' },
                { name: 'two', colour: 'green' },
                { name: 'three', colour: 'blue' },
                { name: 'four', colour: 'yellow' }
            ]
       };
    }
};


const app = new Vue({
    components: {
        custommenu: Menu,
      },
    template: `<custommenu><span class="colour"></span></custommenu>`
});

app.$mount('#app');

这在Vue的v1上运行良好.但是升级到v2后,我看到在同一渲染树中发现了错误"重复存在插槽"默认值-这可能会导致渲染错误

这在v2中是可能的,还是有其他方法可以实现同样的目标?

推荐答案

看起来你需要一个scoped slot,所以你需要用一个scope属性的模板包装你的slot内容:

<custommenu>
  <template scope="colour">
    <span class="colour"></span>
  </template>
</custommenu>

然后需要将其添加到组件模板中的插槽中:

<ul>
  <li v-for="item in options" :class="item.colour">
    <slot colour></slot>
    <span class="label">{{item.name}}</span>
  </li>
</ul>

以下是更新后的JSFIDLE:https://jsfiddle.net/kLge4wun/

Vue.js相关问答推荐

在Nuxt项目中混合Scrolltrigger与Lenis

Vue CDN的html工作,但v—如果不工作

Vue ChildComponent (GrandchildComponent) 应该更新 ParentComponent 的列表

如何在 Vuetify 2 中的轮播项目上放置 href 属性?

我需要在 nuxt2 上使用 /index 作为 url 的一部分

如何将外部 svg 转换为 Vue3 组件?

Vue 3 如何通过多个组件传递插槽

如何在 vue 的 scss 中使用深度 Select 器

使用 vue.js 的 axios 预检失败错误 301

如何从 .vue 文件中导出多个对象

Axios-一次发出多个请求(vue.js)

为什么 vue 文档说 refs 不是响应式的,而实际上它们是响应式的

Vue router路由,Root Vue 没有数据?

触发子函数

带有后退按钮的 Vue.js 路由

vue组件中导入和使用three.js库

Vuejs css 范围性能

如果我刷新我的网页,Vuex store是空的

脚本npm run dev和npm run watch是做什么用的?

在 Vuejs 中放置 firebase.auth().onAuthStateChanged() 的位置