Vue自定义组件-动态组件

本文深入探讨Vue.js中组件的生命周期,包括从创建到销毁的各个阶段,并演示如何使用动态组件来根据条件渲染不同组件,同时展示了组件间的数据传递与事件监听。

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

<template>
  <div class="page-list">
    <span class="list-txt">{{ title }}</span>
    <!-- <ex-btn
      v-if="current == 'ex-btn'"
      v-on:myClick="myClick"
      :msg="msg"
    ></ex-btn>
    <ex-btn2 v-else v-on:myClick="myClick" :msg="msg">
      <img slot="icon" src="xxx.png" />
    </ex-btn2> -->
    <component
      keep-alive
      :is="current"
      v-on:myClick="myClick"
      :msg="msg"
    ></component>
  </div>
</template>
<script>
import btn from './button.vue'
import btn2 from './but2.vue'

export default {
  props: {
    title: { default: '标题' },
    msg: { default: '按钮' },
    current: { default: 'ex-btn' }
  },
  components: {
    'ex-btn': btn,
    'ex-btn2': btn2
  },
  methods: {
    myClick: function () {
      console.log('按钮被点击')
      this.$emit('myClick')
    }
  }
}
</script>

//使用
<template>
  <div id="list">
    <ex-list current="ex-btn2" title="标题1" msg="按钮1"></ex-list>
    <ex-list current="ex-btn" title="标题2" msg="按钮2"></ex-list>
    <ex-list
      current="ex-btn"
      title="标题3"
      msg="按钮3"
      v-on:myClick="test"
    ></ex-list>
    <ex-list
      ref="btnlist"
      current="ex-btn"
      title="标题4"
      msg="按钮4"
      v-on:myClick="test"
    ></ex-list>
  </div>
</template>
<script>
import myList from '../../components/demo/list.vue'
export default {
  name: 'list',
  components: {
    'ex-list': myList
  },
  methods: {
    test: function () {
      console.log('自定义')
      console.log('属性', this.$children)
      console.log('属性', this.$refs.btnlist.title)
    }
  },
  beforeCreate: function () {
    console.log('beforeCreate')
  }, // 组件实例化之前
  created: function () {
    console.log('created')
  }, // 组件实例化了
  beforeMount: function () {
    console.log('beforeMount')
  }, // 组件写入dom结构之前
  mounted: function () { // 组件写入dom结构了
    console.log('mounted')
    console.log(this.$children)
    console.log(this.$refs)
  },
  beforeUpdate: function () {
    console.log('beforeUpdate')
  }, // 组件更新前
  updated: function () {
    console.log('updated')
  }, // 组件更新比如修改了文案
  beforeDestroy: function () {
    console.log('beforeDestroy')
  }, // 组件销毁之前
  destroyed: function () {
    console.log('destroyed')
  }// 组件已经销毁
}
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值