­

Vue自定义组件-动态组件

  • 2019 年 12 月 11 日
  • 笔记
<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>