1 动态组件

①简单来说:

就是几个组件放在一个挂载点下,然后根据父组件的某个变量来决定显示哪个,或者都不显示。

②动态切换:

在挂载点使用component标签,然后使用v-bind:is=”组件名”,会自动去找匹配的组件名,如果没有,则不显示;

改变挂载的组件,只需要修改is指令的值即可。

示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 动态组件</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
    <button @click='toShow'>点击显示子组件</button>
    <component v-bind:is="which_to_show"></component>
</div>
 
<script>
 
// 创建根实例
new Vue({
  el: '#app',
  data:{
      which_to_show:'first'
  },
    methods:{
        toShow:function(){
            var arr = ["first","second","third"];
            var index = arr.indexOf(this.which_to_show);
            if(index<2){
                this.which_to_show = arr[index+1];
            }else{
                this.which_to_show = arr[0];
            }
        }
    },
    components:{
        first:{
            template:'<div>这是子组件1<div>'
        },
        second:{
            template:'<div>这是子组件2<div>'
        },
        third:{
            template:'<div>这是子组件3<div>'
        },
    }
})
</script>
</body>
</html>
View Code

相关文章:

  • 2022-01-01
  • 2021-06-19
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-02
  • 2022-02-10
  • 2022-12-23
  • 2022-02-12
  • 2021-07-29
  • 2021-07-06
相关资源
相似解决方案