Vue内置的Component标签用于动态切换组件

html

     <div id="app">
            <component :is="cut"></component>
            <button @click="current">点击切换</button>
      </div>

js

var classA = {
        template:`<div>状态1</div>`
     };
      var classB = {
        template:`<div>状态2</div>`
     };
      var classC = {
        template:`<div>状态3</div>`
     }
        var vm = new Vue({
            el:"#app",
            data:{
                cut:classA
            },
            methods:{
                current:function(){
                    if(this.cut==classA){
                        this.cut=classB
                    }else if(this.cut==classB){
                        this.cut=classC
                    }else{
                        this.cut=classA
                    } 
                }
            }
           
        })

 

### Vue.js 中内置 `component` 组件的使用 在 Vue.js 中,动态组件通过 `<component>` 元素来实现。这允许根据应用状态的变化加载不同的组件。定义动态组件的关键在于使用特殊的属性 `is` 来指定要渲染哪个组件。 #### 动态切换视图 当有多个组件需要在同一位置显示时,可以利用 `<component :is="currentTabComponent">` 这样的结构[^1]: ```html <template> <div> <!-- 使用 is 特性动态决定展示哪一个 tab --> <button @click="currentTab = 'Home'">Home</button> <button @click="currentTab = 'Posts'">Posts</button> <!-- 动态组件 --> <component :is="currentTab"></component> <!-- Home 和 Posts 是预定义好的组件 --> </div> </template> <script> import Home from './components/Home.vue' import Posts from './components/Posts.vue' export default { components: { Home, Posts }, data() { return { currentTab: "Home" } } } </script> ``` 此代码片段展示了如何创建两个按钮用于切换当前活动标签页的内容。点击任一按钮会改变 `currentTab` 数据项中的值,进而影响到实际被呈现出来的子组件。 #### 带缓存功能的 KeepAlive 为了提高性能并保持组件的状态,在频繁切换相同类型的组件时可采用 `<keep-alive>` 标签包裹住 `<component>` 。这样即使离开了某个页面再回来也不会重新初始化该页面的数据和样式[^3]: ```html <template> <div> <button @click="currentView = 'a'">A</button> <button @click="currentView = 'b'">B</button> <keep-alive> <component :is="currentView"></component> </keep-alive> </div> </template> ``` 上述例子中,如果用户先访问 A 页面然后再跳转至 B 页面之后又返回 A 页面,则 A 页面不会因为再次进入而丢失之前保存下来的信息或状态。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值