vue.js - 父级 v-if="false" 中的 Vue 子级不会被执行,但除了在具有默认插槽的模态包装器中之外,为什么?
问题描述
请看这个最小的例子
1
这个最小模板不会抛出任何错误,因为父级没有渲染任何东西。
<template>
<div v-if="false">
{{ i.dont.have.the.value }}
</div>
</template>
2
现在,如果我使用默认插槽创建模态包装器,并且仍在使用v-if
模态的.vue
<template>
<div v-if="show">
<slot />
</div>
</template>
<script>
export default {
props: {
show: Boolean,
},
};
</script>
但是,这会抛出错误,为什么?
应用程序.vue
<template>
<Modal :show="false">
<div>{{ i.dont.have.the.value }}</div>
</Modal>
</template>
<script>
import Modal from "@/components/Modal.vue";
export default {
components: {
Modal,
},
};
</script>
[Vue warn]: Error in render: "TypeError: Cannot read property 'dont' of undefined"
为什么会这样?
我怎样才能创建一个模态,保证孩子如果不显示就不会被执行?
我不能直接v-if
在 Modal 组件中使用,因为我需要一个过渡。
解决方案
您在插槽中犯了一个错误,App.vue
因为 VueJS 将尝试i.dont.have.the.value
根据父范围解析您的变量(您的插槽没有条件)
记住官方文档中的这条规则
Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
https://vuejs.org/v2/guide/components-slots.html#Compilation-Scope
只需在正确的范围内定义变量就可以了(如果您在子组件中定义它并希望将其公开给父组件,请使用范围插槽)。
推荐阅读
- java - 使用 Spring MVC 将数据从 Thymeleaf 表单保存到数据库的问题
- libgdx - 有没有办法从平铺地图中删除对象?
- vue.js - 访问从 props Vue.js 创建的数据
- angular - 使用Angular 5的具有控件值访问器的子组件中的多个表单控件
- elasticsearch - ElasticSearch 在搜索结果的末尾附加不匹配的文档
- android - 如何断言 UIInstrumentation 测试中的列表视图中是否存在特定值
- c - 谁能向我解释一下这个程序是如何工作的?
- laravel - 使用 Carbon Laravel 将字符串值转换为日期
- kotlin - 交易验证失败。同时使用不同类型的状态作为输入和输出
- android - 可以使用for循环增加字符串的数量吗?安卓工作室