首页 > 解决方案 > 父级 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 组件中使用,因为我需要一个过渡。

标签: vue.jsvuejs2

解决方案


您在插槽中犯了一个错误,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

只需在正确的范围内定义变量就可以了(如果您在子组件中定义它并希望将其公开给父组件,请使用范围插槽)。


推荐阅读