使用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% width: 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM