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)