课程名称:Vue Element+Node.js开发企业通用管理后台系统(第16章)
课程章节: 第16章 Vue进阶(上)
主讲老师:Sam
课程内容:
今天学习的内容包括:
课程收获:
Vue.extend 使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。
<html> <head> <title>Vue.extend 用法</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="root"> <Test :msg="message"></Test> </div> <script> const component = Vue.extend({ template: '<div>{{msg}}</div>', props: { msg: { type: String, default: 'default message' } }, name: 'Test' }) Vue.component('Test') new Vue({ el: '#root', data() { return { message: "Test Extend Component" } } }) </script> </body> </html>
2.Vue.extend 进阶用法
<html> <head> <title>Vue.extend 用法2</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> #loading-wrapper { position: fixed; top: 0; left: 0; display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; background: rgba(0,0,0,.7); color: #fff; } </style> </head> <body> <div id="root"> <button @click="showLoading">显示Loading</button> </div> <script> function Loading(msg) { const LoadingComponent = Vue.extend({ template: '<div id="loading-wrapper">{{msg}}</div>', props: { msg: { type: String, default: msg } }, name: 'LoadingComponent' }) const div = document.createElement('div') div.setAttribute('id', 'loading-wrapper') document.body.append(div) new LoadingComponent().$mount('#loading-wrapper') return () => { document.body.removeChild(document.getElementById('loading-wrapper')) } } Vue.prototype.$loading = Loading new Vue({ el: '#root', methods: { showLoading() { const hide = this.$loading('正在加载,请稍等...') setTimeout(() => { hide() }, 2000) } } }) </script> </body> </html>
Vue.use 用于安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。
<html> <head> <title>Vue.use 用法</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> #loading-wrapper { position: fixed; top: 0; left: 0; display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; background: rgba(0,0,0,.7); color: #fff; } </style> </head> <body> <div id="root"> <button @click="showLoading">显示Loading</button> </div> <script> const loadingPlugin = { install: function(vm) { const LoadingComponent = vm.extend({ template: '<div id="loading-wrapper">{{msg}}</div>', props: { msg: { type: String, default: 'loading...' } } }, 'LoadingComponent') function Loading(msg) { const div = document.createElement('div') div.setAttribute('id', 'loading-wrapper') document.body.append(div) new LoadingComponent({ props: { msg: { type: String, default: msg } } }).$mount('#loading-wrapper') return () => { document.body.removeChild(document.getElementById('loading-wrapper')) } } vm.prototype.$loading = Loading } } Vue.use(loadingPlugin) new Vue({ el: '#root', methods: { showLoading() { const hide = this.$loading('正在加载,请稍等...') setTimeout(() => { hide() }, 2000) } } }) </script> </body> </html>
最后,附上课程截图 ending~