Vue开发中的常用技巧

1. 监听子组件的生命周期
例如有父组件Parent和子组件Child,如果父组件监听到子组件挂载mounted就做一些逻辑处理,常规写法可能如下:

// Parent.vue
<Child @mounted="doSth" />

//Child.vue
mounted(){
  this.$emit('mounted');
}

  

这里提供一种简便的方法,子组件无需做任何处理,只需要在父组件引用子组件时使用@hook方法来监听即可,代码如下:

// Parent.vue
<Child @hook:mounted="doSth" />

methods:{
  doSth(){
    //some codes here
  }
}

当然这里不仅仅是可以监听到mounted,其他生命周期的事件都可以监听到,例如created updated等等。

2.render函数
  1.render函数的作用:
  Vue推荐在绝大数情况下实用模板创建你的HTML,然而当某些特殊场景使用template创建HTML会显得代码繁琐冗长,如根据一个为`level`的prop动态创建标题的 组件,你可能想到这样写:

//Parent.vue
<Child :level="1" >hello world</Child>
//Child.vue
<template>
  <div>
    <h1 v-if="level===1">
      <slot></slot>     </h1>     <h2 v-if="level===2">       <slot></slot>
    </h2>     <h3 v-if="level===3">       <slot></slot>     </h3>     <h4 v-if="level===4">       <slot></slot>     </h4>     <h5 v-if="level===5">       <slot></slot>     </h5>     <h6 v-if="level===6">       <slot></slot>     </h6>   </div> </template>
<script>   export default{     props:["level"]   } </script>

显然template用在这里不合适,我们来看一下用render函数重写这个组件

//Parent.vue
<template>
  <div>
    <Child :level="1">Hello World</Child> 
  </div>
</template>
<script>
  export default {
    component:{
      child:{
        render(creatElement){
          return creatElement(
            'h'+this.level, //标签名称
            {
              style:{
                color:'#f60'
              }
            }, //标签中的属性
            this.$slots.default //子节点数组
          ) 
        },
        props:{
          level:{
            required:true,
            type:Number
          }
        }
      }
    }
  }
</script>

  2.render函数的返回值:Vnode(即虚拟节点)
  3.render函数的参数:createElement
   createElement本身也是一个函数,且有三个参数:
   * 要创建的节点: (必填) { string | object | function },可以是要创建的HTML标签名称,也可以是组件对象,也可以是解析上述任何一种的一个异步函数
   * 标签中的属性: (可选) { object }
   * 子虚拟节点: (可选) { string | array } 由createElement()构建而成,可以使用字符串来生成“文本虚拟节点”

猜你喜欢

转载自www.cnblogs.com/AIonTheRoad/p/11115430.html
今日推荐