Vue(自定义事件+组件)实现简易表单

该博客介绍了一个使用Vue.js实现的购物车组件,组件具有复用性,通过遍历Vue实例对象的数据来填充表单,并通过自定义事件在组件间通信,实现了商品的增删、数量调整及总价计算等功能。用户可以通过全选和单个选择商品,并对选中商品进行操作。代码中还包含了一个用于商品数量加减的子组件。

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

Vue组件实现简易表单

描述:封装Vue组件,组件可以复用,只需改变组件内容,通过遍历vue实例对象内的数据内容,将数据放进组件,并在组件内部通过$emit()将需要操作的事件以及参数传递出去,由父组件接收后再利用vue实例里的函数进行相应操作,注意这里不要直接在组件内部调用vue实例的函数,必须要通过父组件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.css">
    <style>
      .child{
         width: 700px;
         height: 50px;
         display: flex;
         line-height: 50px;
         justify-content: space-between;
      }
    </style>
</head>
<body>
    <div id="bigBox">
        <person :p="list" v-for="list in List" @change="del" @changecount="countall" @chec="ch" @addnum="addnum" @reducenum="reducenum"></person> //调用组件,遍历List数组,将遍历到的每一项用变量p传入组件内部   绑定一系列自定义事件
        <span><input type="checkbox" name="" id=""  @click="checked()" v-model="checkedall"></span><span>总价:{{count}}</span>//全选框
        
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
     var Btn={                         //加减按钮组件
       data(){
           return {
           }
       },
       props:["b"],                     //接收变量b带来的参数
       template:`<div class="chilBtn">
                <button @click="reduce(b.id)">-</button>
                    {{ b.num }}                  //提取b中的数据
                    <button @click="add(b.id)">+</button> 
                </div> 
           `,
        methods:{
              add(id){             
                this.$emit('addnum',id)     //点击过后,传值给父组件   父组件触发名称为addnum的自定义事件
                this.$emit('changesm')   //同上
              },
              reduce(id){
                  this.$emit('reducenum',id)   //点击过后,传值给父组件   父组件触发名称为reducenum的自定义事件
                  this.$emit('changesm')  //同上
              }
           }
    }

    var Person={            //每一条list数据的组件
        data(){
            return {  
            }
        },
        props:["p"],        //接收父组件传进来的p变量的参数
        template:`<div class="child">
               <span><input type="checkbox" name="" id=""  @click="ch(p.id)" v-model="p.check"></span> 
                 <span>
                    {{ p.name }}
                 </span> 
                 <span>
                    {{ p.price }}
                 </span> 
                 <btn :b=p @changesm="countall" @addnum="addnum" @reducenum="reducenum"></btn>     //调用上面的Btn组件,并将p的值用变量b传进去
                 <span>{{p.price*p.num}}</span>
                 <button @click="del(p.id)">删除</button>
                </div> 
           `,
           methods:{
                del(id){
                    this.$emit('change',id)       
                    this.$emit('changecount')
                },
                ch(id){
                    this.$emit('chec',id)
                    this.$emit('changecount')
                },
                countall(){
                    this.$emit('changecount')
                },
                addnum(id){
                    this.$emit('addnum',id)
                },
                reducenum(id){
                    this.$emit('reducenum',id)
                }
           },
        components:{           //要在一个组件内部用别的组件一定要先注册要用的组件
           Btn
        }
    }
   
    var vm=new Vue({
       el:"#bigBox",
       data:{
           checkedall:false,
           count:0,
           List:[{id:"pikaqiu" ,name:"皮卡丘",price:300,num:1,check:false},
                 {id:"huluwa" ,name:"葫芦娃",price:250,num:1,check:false},
                 {id:"xiaowanzi" ,name:"小丸子",price:200,num:1,check:false},
                 {id:"xiaopzhu" ,name:"小P猪",price:120,num:1,check:false}]
       },
       methods:{
            addnum(id){
                let obj = this.List.find((item)=>item.id == id);
                obj.num++
            },
            reducenum(id){
                let obj = this.List.find((item)=>item.id == id);
                let n=obj.num-1
                obj.num = Math.max(n,1)
            },
            countall(){
                this.count=0 
                for(var i=0;i<this.List.length;i++){
                    if(this.List[i].check==true){
                        this.count+=this.List[i].num*this.List
                        [i].price
                    }
                }
            },
            del(id){
                    this.List = this.List.filter((item)=>{  
                    return item.id != id
                })
            },
            checked(){          //勾选全选框时,将所有复选框选中
                if(this.checkedall==false){
                    for(var i=0;i<this.List.length;i++){
                        this.List[i].check=true
                    }
                }else{
                    for(var i=0;i<this.List.length;i++){
                        this.List[i].check=false
                    }
                }
                this.countall()
            },
            ch(id){         //实现多选框勾选时遍历判断是否是全选,是的话就自动勾选全选框
                var n=0;
                let obj = this.List.find((item)=>item.id == id);
                obj.check=!obj.check
                for(var i=0;i<this.List.length;i++){
                        if(this.List[i].check==true){
                             n++
                        }
                    }
                    if(n==this.List.length){
                        this.checkedall=true
                    }else{
                        this.checkedall=false
                    }
            }
       },
       components:{ 
           Person,Btn
        }
    })
    
</script>
</html>

注:初学vue,此代码很多地方还需优化

效果图:
在这里插入图片描述

<think>我们正在讨论Vue 3中创建简易表单实现自定义组件。根据用户需求,我们需要创建一个简单的表单,并展示如何创建自定义组件。 步骤: 1. 创建一个Vue 3项目(如果已有项目可跳过) 2. 创建自定义表单组件(例如一个自定义输入框) 3. 在表单中使用自定义组件 4. 实现数据绑定事件处理 注意:Vue 3中通常使用Composition API(setup语法)编写组件。 示例: 我们将创建一个自定义文本输入组件,然后在父组件表单)中使用它。 第一步:创建自定义输入组件(例如命名为CustomInput.vue) 第二步:在父表单组件中引入并使用,同时处理数据绑定。 引用说明:根据用户提供的引用[2],我们了解到在Vue自定义组件并全局注册的方法(使用Vue.component)。但Vue 3中推荐使用应用实例的component方法进行全局注册,或者局部注册。 由于用户要求简易表单,我们采用局部注册。 具体代码实现: 1. 自定义输入组件 CustomInput.vue: 这个组件将接收一个modelValue(用于v-model绑定),并触发update:modelValue事件。同时,我们也可以添加一些自定义样式和属性。 2. 表单组件(例如FormPage.vue): 在这个组件中,我们将使用CustomInput组件,并绑定表单数据。 考虑到用户可能需要表单详情组件,我们可以参考引用[2]中的formlist组件思路,但这里我们简化处理,只做一个基础示例。 开始编写代码示例:</think>### Vue 3 简易表单自定义组件教程 下面我将逐步指导你使用 Vue 3 创建简易表单实现自定义组件: #### 步骤 1:创建 Vue 3 项目 ```bash npm create vue@latest # 选择默认配置或按需选择 cd your-project npm install ``` #### 步骤 2:创建自定义表单组件 在 `src/components` 目录下创建 `CustomInput.vue`: ```vue <template> <div class="custom-input"> <label v-if="label">{{ label }}</label> <input :type="type" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" :placeholder="placeholder" /> <p v-if="error" class="error">{{ error }}</p> </div> </template> <script setup> defineProps({ modelValue: [String, Number], label: String, type: { type: String, default: 'text' }, placeholder: String, error: String }) defineEmits(['update:modelValue']) </script> <style scoped> .custom-input { margin-bottom: 1rem; } .error { color: red; font-size: 0.8rem; } </style> ``` #### 步骤 3:创建表单页面组件 在 `src/views` 目录下创建 `FormPage.vue`: ```vue <template> <form @submit.prevent="handleSubmit"> <CustomInput label="姓名" v-model="formData.name" placeholder="请输入姓名" :error="errors.name" /> <CustomInput label="邮箱" v-model="formData.email" type="email" placeholder="请输入邮箱" :error="errors.email" /> <CustomInput label="密码" v-model="formData.password" type="password" placeholder="请输入密码" :error="errors.password" /> <button type="submit">提交</button> </form> </template> <script setup> import { reactive } from 'vue' import CustomInput from '@/components/CustomInput.vue' const formData = reactive({ name: '', email: '', password: '' }) const errors = reactive({ name: '', email: '', password: '' }) const validateForm = () => { let isValid = true if (!formData.name.trim()) { errors.name = '姓名不能为空' isValid = false } else { errors.name = '' } if (!/^\S+@\S+\.\S+$/.test(formData.email)) { errors.email = '请输入有效的邮箱地址' isValid = false } else { errors.email = '' } if (formData.password.length < 6) { errors.password = '密码长度至少6位' isValid = false } else { errors.password = '' } return isValid } const handleSubmit = () => { if (validateForm()) { console.log('表单提交数据:', formData) // 这里可以添加API提交逻辑 alert('表单验证通过!') } } </script> ``` #### 步骤 4:注册并使用组件 在 `src/main.js` 中全局注册组件(可选): ```javascript import { createApp } from 'vue' import App from './App.vue' import CustomInput from '@/components/CustomInput.vue' const app = createApp(App) app.component('CustomInput', CustomInput) app.mount('#app') ``` 或者在需要的组件中局部注册: ```vue <script setup> import CustomInput from '@/components/CustomInput.vue' </script> ``` #### 步骤 5:在路由中使用表单页面 在 `src/router/index.js` 中添加路由: ```javascript import { createRouter, createWebHistory } from 'vue-router' import FormPage from '@/views/FormPage.vue' const routes = [ { path: '/form', name: 'form', component: FormPage } ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` #### 关键概念说明: 1. **v-model 双向绑定**: - 自定义组件中使用 `modelValue` prop 和 `update:modelValue` 事件实现 - 父组件通过 `v-model="formData.name"` 绑定数据 2. **组件通信**: - 使用 `defineProps` 声明接收的属性 - 使用 `defineEmits` 声明自定义事件 3. **表单验证**: - 在提交时触发的 `validateForm` 方法 - 实时错误反馈机制 4. **样式封装**: - 使用 `scoped` 属性确保组件样式隔离 - BEM 命名规范(示例中的 `.custom-input`) #### 进阶优化建议: 1. 添加表单重置功能 2. 实现实时验证(使用 `watch` 或 `computed`) 3. 集成表单验证库如 VeeValidate 4. 添加提交状态指示(加载动画) 5. 创建自定义下拉框、单选按钮等更多表单组件 这个实现遵循了 Vue 3 的 Composition API 最佳实践,组件结构清晰且易于扩展。自定义输入组件可复用,表单验证逻辑完整,样式采用作用域 CSS 避免冲突[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大兵的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值