vue的动画封装,vue的递归组件

在项目中,许多地方会使用到类似的动画,所以我们封装起来会好点,我们先创建一个组件,用来设置它的动画效果,

<template>
    <transition name="fade" @before-enter="handleBeforeEnter" @enter="handleEnter">
        <slot v-if="show"></slot>
    </transition>
</template>

<script>
export default {
    props:['show'],
    methods:{
        handleBeforeEnter:function(el){
            el.style.color='red'
        },
        handleEnter:function(el,done){
            setTimeout(()=>{
                el.style.color='green',
                done()
            },2000)
        }
    }
}
</script>

设置一个组件,动画效果用js来定义,我们接受来自父组件的参数(show),再来控制我们子组件的显示与隐藏。

我们在子组件中设置了插槽slot ,让父元素决定需要执行动画的dom元素。

此时我们来设置父组件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
    </ul>
    <h2>Ecosystem</h2>
      <child :show="show">
        <div>show child</div>
      </child>
    <button @click="clickTr">点击切换</button>  
  </div>
</template>

<script>
import child from './child.vue'  //引入子组件
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'write you first vue ',
     show:true
    }
  },
  methods:{
    clickTr:function(){
      this.show=!this.show;
    }
   
  },
  components:{//注册组件
    child,
  }

}
</script>

我们需要在父组件中要引入子组件(from后面跟的是路径,你根据自己的文件位置填写路径和子组件名),然后我们的父组件需要注册组件 components引入,然后在父组件template中把子组件添加进去,在子组件中添加需要显示的元素;重点我们要在子组件中添加:show=“show”  这里是 :传递子组件的值(也就是子组件props接收的值)=“父组件的data的某属性”;在父组件中设置methods方法,用来控制样式的显示与隐藏,我们可以在下面定义一个按钮,绑定一个点击事件,来控制父组件的data的某属性的值;此时我们就拥有了一个封装的动画。

vue中我们会获取到后端传递过来的,多组嵌套值,这时候我们可以使用vue的递归组件来实现。

<template>
  <div>
    <div
      class="item"
      v-for="(item, index) of list"
      :key="index"
    >
      <div class="item-title border-bottom">
        <span class="item-title-icon"></span>
        {{item.title}}
      </div>
      <div v-if="item.children" class="item-chilren">
        <detail-list :list="item.children"></detail-list>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DetailList',
  props: {
    list: Array
  }
}
</script>

我们在定义组件时填写的name名字就是我们可以递归复用的值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值