[英]Use parent slot variables in Vue template slot
I have a simple FormComponent
:我有一个简单的
FormComponent
:
<template>
<form>
<fieldset>
<slot />
</fieldset>
<span v-if="!isEditing" @click="edit()">Edit</span>
</form>
</template>
<script>
export default {
data () {
return {
isEditing: false,
}
},
methods: {
edit (state) {
this.isEditing = !this.isEditing
}
}
}
</script>
And when I use the component:当我使用组件时:
<FormComponent>
<input value="Man" type="text" :disabled="!isEditing">
</FormComponent>
The input field are correctly slotted into the component but the :disabled="!isEditing"
from the slot isn't reacting to the change of isEditing
in the FormComponent
.输入字段已正确插入组件,但插槽中的
:disabled="!isEditing"
没有对isEditing
中FormComponent
的更改做出反应。
The Vue documentation is pretty good, but it doesn't cover each edge case. Vue 文档非常好,但它并没有涵盖每个边缘情况。
The component with the <slot></slot>
tag has to bind the data onto an attribute on the <slot>
tag, like a prop:带有
<slot></slot>
标签的组件必须将数据绑定到<slot>
标签上的一个属性上,就像一个道具:
<slot :isEditing="isEditing"></slot>
Then when you render that slotted component, Vue creates and exposes an object containing all of the bound data, with each attribute having a property on that object.然后,当您渲染该开槽组件时,Vue 创建并公开一个包含所有绑定数据的 object,每个属性在该 object 上都有一个属性。
Access the object by adding an expression to the v-slot
directive in this format:通过以这种格式向
v-slot
指令添加表达式来访问 object:
<FormComponent v-slot:default="slotProps">
(Or use the alias #
as in #default="slotProps"
.) You can access individual properties like isEditing
via that object, like slotProps.isEditing
: (或在
#default="slotProps"
中使用别名#
。)您可以通过 object 访问单个属性,例如isEditing
,例如slotProps.isEditing
:
<FormComponent #default="slotProps">
<input value="Man" type="text" :disabled="!slotProps.isEditing">
</FormComponent>
Here's the more common (and versatile) <template>
syntax:这是更常见(和通用)的
<template>
语法:
<FormComponent>
<template #default="slotProps">
<input value="Man" type="text" :disabled="!slotProps.isEditing">
</template>
</FormComponent>
You can also destructure slotProps
for more direct access to the properties:您还可以解构
slotProps
以更直接地访问属性:
<FormComponent>
<template #default="{ isEditing }">
<input value="Man" type="text" :disabled="!isEditing">
</template>
</FormComponent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.