首页 > 解决方案 > 如何使用 v-bind 为 url 属性绑定插槽?

问题描述

如何将属性从组件传递到插槽?

这是在组件中

<navigation-link url="/profile">
  Your Profile
</navigation-link>

然后在模板中我想使用 url

<template>
  <div>
    <a
      v-bind:href="url"
      class="nav-link">
      <slot></slot>
    </a>
    <span class="active></span>
  <div>
</template>

根据文档,这应该可以工作,但是我得到了错误:Property or method "url" is not defined on the instance but referenced during render.

标签: vue.jsvue-component

解决方案


我认为您想将文本“您的个人资料”放入<slot></slot>

因此,为此,您需要这样做。

<navigation-link url="/profile">
   <template slot="text">
      Your Profile
   </template>
</navigation-link>

在组件中,像这样命名插槽

<template>
  <div>
    <a
      v-bind:href="url"
      class="nav-link">
      <slot name="text" />
    </a>
    <span class="active></span>
  <div>
</template>

大概,这个作品。

编辑:

根据文档,这应该可以工作,但我得到错误:属性或方法“url”未在实例上定义,但在渲染期间被引用。

那是因为,你没有在组件中声明 url,你可能需要把

props: ['url'],
data() {
 return {
    propUrl: this.url
  }
}

并在模板中使用 this.propUrl

问候


推荐阅读