Vue clicks the button to dynamically create and delete components

Main functional requirements:

  1. Click the component library button on the left to create corresponding different components, and display them in the right area
  2. Click the delete button in the component created on the right to delete the corresponding component
  3. After deleting the corresponding component, the position of the component below automatically moves up

Effect picture:

-Insert picture

Code:

  1. Parent component code (with the css style code removed):
<template>
  <div class="home">
    <div class="container">
      <div class="addZujian">
        <div>
          <span>组件库</span>
          <span style="color:#bbb;margin-left:10px;font-size:14px;">点击使用</span>
        </div>
        <div class="zujianBtn" @click="zujian">添加组件1</div>
        <div class="zujianBtn" @click="zujian2">添加组件2</div>
      </div>
      <div class="zujianContent">
        <div>组件展示区</div>
        <!-- Vue提供了 component ,来展示对应名称的组件 -->
        <!-- component 是一个占位符, :is 属性,可以用来指定要展示的组件的名称 -->
        <component
          v-for="(item,index) in comName"
          :is="item.name"
          :key="index"
          @func="getContent(index)"
        ></component>
      </div>
    </div>
  </div>
</template>
<script>
// 引入子组件
import zujian1 from "./zujian";
import zujian2 from "./zujian2";
export default {
    
    
  data() {
    
    
    return {
    
    
      comName: []
    };
  },
  components: {
    
    
    zujian1,
    zujian2
  },
  methods: {
    
    
    // 添加组件1
    zujian() {
    
    
      this.comName.push({
    
    
        name: "zujian1"
      });
    },
    // 添加组件2
    zujian2() {
    
    
      this.comName.push({
    
    
        name: "zujian2"
      });
    },
    // 删除组件
    getContent(index) {
    
    
      this.comName.splice(index, 1);
    }
  }
};
</script>
  1. Subcomponent 1 code (with the css style code removed):
<template>
  <div class="home">
    <div class="container">
      <span>我是组件1</span>
      <span class="del" @click="del">删除组件</span>
    </div>
  </div>
</template>
<script>
export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  methods: {
    
    
    del() {
    
    
      // 子组件向父组件传值(此处传递一个空值) - 父组件将执行getContent方法
      this.$emit('func','')
    }
  }
};
</script>
  1. Sub-component 2 code (with the css style code removed):
<template>
  <div class="home">
    <div class="container">
      <span>我是组件2</span>
      <span class="del" @click="del">删除组件</span>
    </div>
  </div>
</template>
<script>
export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  methods: {
    
    
    del() {
    
    
      // 子组件向父组件传值(此处传递一个空值) - 父组件将执行getContent方法
      this.$emit("func", "");
    }
  }
};
</script>
Web front-end communication QQ group: 327814892

Guess you like

Origin blog.csdn.net/qq_43327305/article/details/103731533