Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue 动态组件

作者:傲骨依旧   发布日期:2025-10-08   浏览:18

<template>
  <div>
    <!-- 使用动态组件,通过 v-bind:is 绑定当前组件名称 -->
    <component :is="currentComponent"></component>

    <!-- 切换按钮 -->
    <button @click="changeComponent('Home')">Home</button>
    <button @click="changeComponent('About')">About</button>
  </div>
</template>

<script>
// 定义两个简单组件
const Home = {
  template: '<div>Welcome to the Home page!</div>'
}

const About = {
  template: '<div>Welcome to the About page!</div>'
}

export default {
  data() {
    return {
      // 当前显示的组件名称
      currentComponent: 'Home'
    }
  },
  methods: {
    // 切换组件的方法
    changeComponent(componentName) {
      this.currentComponent = componentName
    }
  },
  components: {
    // 注册组件
    Home,
    About
  }
}
</script>

解释说明:

  1. 动态组件:使用 <component> 标签并通过 v-bind:is 动态绑定组件名称来实现动态组件。currentComponent 是一个数据属性,用于存储当前要显示的组件名称。

  2. 切换按钮:通过点击按钮调用 changeComponent 方法来改变 currentComponent 的值,从而切换显示不同的组件。

  3. 组件定义:在 components 中注册了两个简单的组件 HomeAbout,每个组件都有自己的模板。

  4. 方法changeComponent 方法接收一个参数(组件名称),并将其赋值给 currentComponent,从而实现组件的切换。

这样,你可以根据需要动态地加载和切换不同的组件。

上一篇:vue3 ref和reactive的区别

下一篇:vue3动态路由

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站