Vue Js 组件语法

问题描述 投票:0回答:3
javascript vue.js dom
3个回答
1
投票

正如您提到的,有两种使用自定义组件的方法。

如果我们不传递任何子元素,我们通常使用

self-closing tag
组件

如果您需要将子组件传递给组件,则必须使用第二种方法。组件内的子组件称为

slot

您可以在this文章

中阅读有关插槽(又名子组件)的更多信息

1
投票

Component
标签内的HTML标记将转到组件中定义的插槽。 所以,如果
Component
定义如下

<template>
<h1>This is content of component</h1>
<slot></slot>
</template>

并在父组件中使用如下

<template>
  <Component>
    <div> 
      Hello I am a div 
    </div>
  </Component>
</template>

然后下面的内容将会被实际渲染

<h1>This is content of component</h1>
<div> 
  Hello I am a div 
</div>

0
投票

您可以通过两种方式在父组件中渲染该组件:

1)

<template>
  <div>
    <p>we are in parent component</p>
    <CustomComponent />
  </div>
</template>

或 2)

<template>
  <div>
    <p>we are in parent component</p>
    <CustomComponent></CustomComponent>
  </div>
</template>

现在,如果您需要将自定义内容放入子组件中,可以使用 vue.js“slot” 来实现。

这就是它的工作原理:

// Child component: which is a button that we want to put a custom icon inside it
// componentName: CustomBtn
<template>
  <button class="flex gap-x-2 items-center">
    <span>Click here</span>
    <slot />
  </button>
</template>

现在在父组件内部:

<template>
  <CustomBtn>
    <!-- everything inside here, will be passed to the Slot -->
    <i class="fa fa-pencil"></i>
  </CustomBtn>
</template>

Vue Js 会将其编译为:

<button class="flex gap-x-2 items-center">
    <span>Click here</span>
    <i class="fa fa-pencil"></i>
</button>
© www.soinside.com 2019 - 2024. All rights reserved.