• 使用Vue.extend来动态创建组件


    Vue.extend( options )

    参数:{Object} options

    用法:使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象

    data 选项是特例,需要注意 - 在 Vue.extend() 中它必须是函数

    <div id="aa"></div>
    
    // 创建构造器
    var Profile = Vue.extend({
      template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
      data: function () {
        return {
          firstName: '',
          lastName: '',
          alias: '李四'
        }
      }
    })
    // 创建 Profile 实例,并挂载到一个元素上。
    new Profile().$mount('#aa')

    实例需求:利用其制作一个 点击按钮,出现弹框 【如图】。

    ToaList组件:
    
    <template>
    <div class="container" v-if="show"> <div>{{ text }}</div> </div>
    </template> <script> export default { data() { return {} } } </script> <style lang="stylus" scoped> .container { position: fixed; top: 50% left: 50% 100px height: 40px text-align center line-height 40px color #fff background-color rgba(0, 0, 0, .8) border-radius 10px box-sizing border-box }
    主组件:
    <template>
      <div id="app">
        <button class="btn" @click="clickMe">点我</button>
        <router-view />
      </div>
    </template>
    <script>
    export default {
      data() {
        return {};
      },
      methods: {
        clickMe() {
        //传入值
    this.$toast("你好啊!") } }, }; </script> <style lang="stylus"> #app { display: flex; justify-content: center; align-items: centerS; } </style>

    新建一个toalist.js文件

    import Vue from "vue"
    import Toast from "./toalist.vue";
    
    console.log(Toast);
    //根据对象创建组件构造器
    const ToastConstructor = Vue.extend(Toast);
    
    function showsToast(texts) {
        const toastDOM = new ToastConstructor({
            el: document.createElement("div"),
            data() {
                return {
                    text: texts,
                    show: true,
                }
            }
        });
        // console.log(toastDOM);
        document.body.appendChild(toastDOM.$el);
        setTimeout(() => {
            toastDOM.show = false;
        }, 2000)
    }
    
    function toastRegisty(){
        Vue.prototype.$toast = showsToast
    }
    export default toastRegisty;

    在main.js引入

    import toastRegisty from "./toalist.js"
    Vue.use(toastRegisty)
  • 相关阅读:
    Python实现栈、队列、双端队列
    Redis主从配置、数据持久化、集群
    Redis安装,数据类型及常用命令
    nginx+uwsgi环境部署
    Nginx负载均衡、location匹配
    Nginx安装、多域名访问
    Linux-mysql的备份与恢复
    Linux-mysql主从复制
    Python dumps()的使用
    Python rpush()函数
  • 原文地址:https://www.cnblogs.com/0520euv/p/13893723.html
Copyright © 2020-2023  润新知