vue组件嵌套组件不显示_动态显示Vue组件

本文探讨了在Vue中遇到组件不显示的问题,重点介绍了如何使用条件指令`v-if`和`v-else`以及`component`与`:is`属性来动态显示组件。通过`v-if`检查计算属性决定组件是否显示,并展示了条件语句的嵌套使用。同时,提到了`<component :is="动态组件名">`的方式来动态分配组件,其中`动态组件名`是状态的一部分或计算属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue组件嵌套组件不显示

使用条件指令 (Using conditional directives)

The simplest option is to use the v-if and v-else directives.

最简单的选择是使用v-ifv-else指令。

Here’s an example. The v-if directive checks the noTodos computed property, which returns false if the state property todos contains at least one item:

这是一个例子。 v-if指令检查noTodos计算属性,如果state属性todos包含至少一项,则返回false:

<template>
  <main>
    <AddFirstTodo v-if="noTodos" />
    <div v-else>
      <AddTodo />
      <Todos :todos=todos />
    </div>
  </main>
</template>

<script>
export default {
  data() {
    return {
      todos: [],
    }
  },
  computed: {
    noTodos() {
      return this.todos.length === 0
    }
  }
}
</script>

This allows to solve the needs of many applications without reaching for more complex setups. Conditionals can be nested, too, like this:

这样可以解决许多应用程序的需求,而无需进行更复杂的设置。 条件语句也可以嵌套,如下所示:

<template>
  <main>
    <Component1 v-if="shouldShowComponent1" />
    <div v-else>
      <Component2 v-if="shouldShowComponent2" />
      <div v-else>
        <Component3 />
      </div>
    </div>
  </main>
</template>

使用component Component and is (Using the component Component and is)

Instead of creating v-if and v-else structures, you can build your template so that there’s a placeholder that will be dynamically assigned a component.

您可以构建模板,而不是创建v-ifv-else结构,以便有一个占位符将动态分配给组件。

That’s what the component component does, with the help of the v-bind:is directive.

这就是component组件在v-bind:is指令的帮助下所做的事情。

<component v-bind:is="componentName"></component>

componentName is a property of the state that identifies the name of the component that we want to render. It can be part of the state, or a computed property:

componentName是状态的属性,用于标识我们要呈现的组件的名称。 它可以是状态的一部分,也可以是计算属性:

<script>
export default {
  data() {
    return {
      componentName: 'aComponent',
    }
  }
}
</script>

翻译自: https://flaviocopes.com/vue-dynamically-show-components/

vue组件嵌套组件不显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值