vue进阶—1.vue组件化实践

1.1组件化

vue组件系统提供了一种抽象,让我们可以使用独立可复用的组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树。组件化能提高开发效率,方便重复使用,简化调试步骤,提升项目可维护性,便于多人协同开发
在这里插入图片描述

1.1.1 组件通信的常用方式

props
父给子传值

//child
props:{msg:String}

//parent
<HelloWorld msg="Welcome to Your Vue.js App">

子给父传值

//child
this.$emit('add',good)
//parent
<Cart @add="cartAdd($event)"></Cart>

eventbus(事件总线)
任意两个组件之间的传值常用事件总线或Vuex的方式

//Bus:事件派发、监听和回调管理
class Bus{
    constructor(){
        this.callback = {}
    }
    $on(name,fn){
        this.callbacks[name] = this.callbacks[name]||[]
        this.callbacks[name].push(n)
    }
    $emit(name,args){
        if(this.callbacks[name]){
            this.callbacks[name].forEach(cb=>cb(args)))
        }
    }
}
//mian.js
Vue.prototype.$bus = new Bus()
//child1
this.$bus.$on('foo',handle)
//child2
this.$bus.$emit('foo')

实践中通常用Vue替换Bus,因为Vue已经实现了相应的接口
vuex
创建唯一的全局数据管理者store,通过它管理数据并通知组件状态的变更
自定义事件
边界事件

p a r e n t / parent/ parent/root

兄弟组件之间的通信可通过共同的祖辈搭桥, p a r e n t / parent/ parent/root

//brother1
this.$parent.$on('foo',handle)
//brother2
this.$parent.$emit('foo')

** c h i l d r e n ∗ ∗ 父 组 件 可 以 通 过 children** 父组件可以通过 childrenchildren访问子组件实现父子通信(注意$children不能保证子元素的顺序)

//parent
this.$children[0].xx = 'xxx'

$refs
获取子节点引用

//parent
<HelloWorld ref="hw">

mounted(){
    this.$refs.hw.xx='xxx'
}

provide/inject
能够实现祖先和后代之间的传值

//ancestor
provide(){
    return {foo:'foo'}
}
//descendant
inject:['foo']

非props属性
a t t r s / attrs/ attrs/listeners
包含了父作用域不作为prop被识别(且获取)的特性绑定(class和style除外),当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class和style除外),并且可以通过v-bind="$attrs"传入内部组件–在创建高级别的组件时非常有用。

//child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
//parent
<HelloWorld foo="foo" />

1.2插槽

插槽语法是Vue实现内容分发的API,用于复合组件的开发,该技术在通用组件开发库中有大量应用
匿名插槽

//comp
<div>
    <slot></slot>
</div>
//parent
<comp>hello</comp>

具名插槽
将内容分发到子组件的指定位置

//comp2
<div>
    <slot></slot>
    <slot name="content"></slot>
</div>
//parent
<Comp2>
    <!-- 默认插槽使用default做参数-->
    <template v-slot:default></template>
    <!-- 具名插槽用插槽名做参数-->
    <tempalte v-slot:content>内容...</template>
</Comp2>

作用域插槽
分发内容要用到子组件中的数据

//comp3
<div>
    <slot :foo = "foo"></slot>
</div>
//parent
<Comp3>
    <!--把v-slot的值指定为作用域上下文-->
    <template v-slot:default="slotProps">
    来自子组件数据:{{slotProps.foo}}
    </template>
</Comp3>

1.3组件化实战

实现KFrom

//components/form/KInput.vue
<template>
  <div>
    <input :type="type" :value="value" @input="onInput" v-bind="$attrs"/>
  </div>
</template>

<script>
export default {
  inheritAttrs:false,//设置为false避免设置到根元素上
  props:{
    value:{
      type:String,
      default:''
    },
    type:{
      type:String,
      default:'text'
    }
  },
  methods:{
    onInput(e){
      //派发一个input事件即可
      this.$emit('input',e.target.value)

      //通知父级进行检验
      this.$parent.$emit('validate')
    }
  }
}
</script>

<style scoped>

</style>
//components/form/KFormItem.vue
<template>
  <div>
    <label v-if="label">{{label}}</label>
    <slot></slot>
    <!--校验信息显示-->
    <p v-if="error">{{error}}</p>
  </div>
</template>

<script>
//async-validator
import Schema from "async-validator"

export default {
  inject:["form"],
  data(){
    return {
      error:""
    }
  },
  props:{
    label:{
      type:String,
      default:""
    },
    prop:{
      type:String
    }
  },
  methods:{
    validate(){
      //规则
      const rules = this.form.rules[this.prop]
      //当前值
      const value = this.form.model[this.prop]
      const desc = {[this.prop]:rules};
      //创建schema实例
      const schema = new Schema(desc);
      return schema.validate({[this.prop]:value},error=>{
        if(error){
          console.log(error)
          this.error = error[0].message
        }else{
          this.error = ""
        }
      })
    }
  },
  mounted(){
    this.$on("validate",()=>{
      this.validate()
    })
  }
}
</script>

<style scoped>

</style>
//components/form/KFormForm.vue
<template>
  <div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  provide(){
    return {
      form:this
    }
  },
  props:{
    model:{
      type:Object,
      required:true
    },
    rules:{
      type:Object
    }
  },
  methods:{
    validate(cb){
      const tasks = this.$children
      .filter(item=>item.prop)//过滤掉没有prop属性的Item
      .map(item=>item.validate());
      Promise.all(tasks)
      .then(()=>cb(true))
      .catch(()=>cb(false))
    }
  }
}
</script>
//Notice.vue
<template>
  <div class="box" v-if="isShow">
    <h3>{{title}}</h3>
    <p class="box-content">{{message}}</p>
  </div>
</template>

<script>
export default {
  props:{
    title:{
      type:String,
      default:""
    },
    message:{
      type:String,
      default:""
    },
    duration:{
      type:Number,
      default:1000
    }
  },
  data(){
    return {
      isShow:false
    }
  },
  methods:{
    show(){
      this.isShow = true;
      setTimeout(this.hide,this.duration);
    },
    hide(){
      this.show = false;
      this.remove();
    }
  }
}
</script>

<style scoped>
  .box{
    position:fixed;
    width:100%;
    top:16px;
    left:0;
    text-align:center;
    pointer-events: none;
    background-color: white;
    border:grey 3px solid;
    box-sizing: border-box;
  }
  .box-content{
    width:200px;
    margin:10px auto;
    font-size:14px;
    padding:8px 16px;
    background:#fff;
    border-radius:3px;
    margin-bottom:8px;
  }
</style>
//create
import Vue from 'vue'

function create(Component,props){
  const vm =new Vue({
    render:h=>h(Component,{props})
  }).$mount() // 不指定宿主元素,则会创建真实dom,但是不会追加操作

  document.body.appendChild(vm.$el)

  const comp = vm.$children[0]

  comp.remove = ()=>{
    document.body.removeChild(vm.$el)
    vm.$destroy()
  }

  return comp
}

export default create
//index.vue
<template>
  <div>
    <!-- <element-test></element-test> -->

    <!-- KForm -->
    <KForm :model="userInfo" :rules="rules" ref="loginForm">
      <KFormItem label="用户名" prop="username">
        <KInput v-model="userInfo.username" placeholder="请输入用户名"/>
      </KFormItem>
      <KFormItem label="密码" prop="password">
        <KInput  type="password" v-model="userInfo.password" placeholder="请输入密码"/>
      </KFormItem>
      <KFormItem>
        <button @click="login">登录</button>
      </KFormItem>
    </KForm>
  </div>
</template>

<script>
// import ElementTest from "@/components/form/ElementTest.vue"
import KForm from "@/components/form/KForm.vue"
import KFormItem from "@/components/form/KFormItem.vue"
import KInput from "@/components/form/KInput.vue"
import Notice from "@/components/form/Notice.vue"

export default {
  data(){
    return {
      userInfo: {
        username: "tom",
        password: ""
      },
      rules: {
        username: [{ required: true, message: "请输入用户名称" }],
        password: [{ required: true, message: "请输入密码" }]
      }
    }
  },
  components:{
    // ElementTest,
    KForm,
    KFormItem,
    KInput
  },
  methods:{
    login(){
      this.$refs["loginForm"].validate(valid=>{
          const notice = this.$create(Notice,{
            title:"提示",
            message:valid?"请你登录!":"效验失败!",
            duration:2000
          });
          notice.show();
      })
    }
  }
}
</script>

<style scoped>

</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值