面试被问到Vue?想进一步提升?那就停下来看一下吧

开发 前端
在开发和设计一个组件的时候有可能就会绕一个大圈子,所以我非常推荐各位在学习Vue的时候先要对Vue核心的所有API都有一个了解。这篇文章我会从实践出发,遇到一些知识点会顺带总结一下。

[[274374]]

Vue作为最近最炙手可热的前端框架,其简单的入门方式和功能强大的API是其优点。而同时因为其API的多样性和丰富性,所以他的很多开发方式就和一切基于组件的React不同,如果没有对Vue的API(有一些甚至文档都没提到)有一个全面的了解,那么在开发和设计一个组件的时候有可能就会绕一个大圈子,所以我非常推荐各位在学习Vue的时候先要对Vue核心的所有API都有一个了解。这篇文章我会从实践出发,遇到一些知识点会顺带总结一下。文章很长,一次看不完可以先收藏,如果你刚入门vue,那么相信这篇文章对你以后的提升绝对有帮助。

进入正题,我相信不论什么项目几乎都会有一个必不可少的功能,就是用户操作反馈、或者提醒,像这样(简单的一个demo)。

其实在vue的中大型项目中,这些类似的小功能会更加丰富以及严谨,而在以Vue作为核心框架的前端项目中,因为Vue本身是一个组件化和虚拟Dom的框架,要实现一个通知组件的展示当然是非常简单的。但因为通知组件的使用特性,直接在模板当中书写组件并通过v-show或者props控制通知组件的显示显然是非常不方便的并且这样意味着你的代码结构要变,当各种各样的弹层变多的时候,我们都将其挂载到APP或者一个组件下显然不太合理,而且如果要在action或者其他非组件场景中要用到通知,那么纯组件模式的用法也无法实现。那么有没有办法即用到Vue组件化特性方便得实现一个通知组件的展现,那么我们可否用一个方法来控制弹层组件的显示和隐藏呢?

目标一

实现一个简单的反馈通知,可以通过方法在组件内直接调用。比如Vue.$confirm({...obj})

首先,我们来实现通知组件,相信这个大部分人都能写出来一个像模像样的组件,不啰嗦,直接上代码:

  1. <template>  
  2.     <div  
  3.         :class="type"  
  4.         class="eqc-notifier">  
  5.         <i  
  6.             :class="iconClass"  
  7.             class="icon fl"/>  
  8.         <span>{{ msg }}</span>  
  9.     <!-- <span class="close fr eqf-no" @click="close"></span> -->  
  10.     </div>  
  11. </template>  
  12. <script>  
  13. export default {  
  14.     name: 'Notification',  
  15.     props: {  
  16.         type: {  
  17.             type: String,  
  18.             default: ''  
  19.         },  
  20.         msg: {  
  21.             type: String,  
  22.             default: ''  
  23.         }  
  24.     },  
  25.     computed: {  
  26.         iconClass() {  
  27.             switch (this.type) {  
  28.                 case 'success':  
  29.                     return 'eqf-info-f'  
  30.                 case 'fail':  
  31.                     return 'eqf-no-f'  
  32.                 case 'info':  
  33.                     return 'eqf-info-f'  
  34.                 case 'warn':  
  35.                     return 'eqf-alert-f'  
  36.             }  
  37.         }  
  38.     },  
  39.     mounted() {  
  40.         setTimeout(() => this.close(), 4000)  
  41.     },  
  42.     methods: {  
  43.         close() {  
  44.         }  
  45.     }  
  46.  
  47. </script>  
  48. <style lang="scss">  
  49.     .eqc-notifier {  
  50.         position: fixed;  
  51.         top: 68px;  
  52.         left: 50%;  
  53.         height: 36px;  
  54.         padding-right: 10px;  
  55.         line-height: 36px;  
  56.         box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.16);  
  57.         border-radius: 3px;  
  58.         background: #fff;  
  59.         z-index: 100; // 层级最高  
  60.         transform: translateX(-50%);  
  61.         animation: fade-in 0.3s;  
  62.     .icon {  
  63.         margin: 10px;  
  64.         font-size: 16px;  
  65.     }  
  66.     .close {  
  67.         margin: 8px;  
  68.         font-size: 20px;  
  69.         color: #666;  
  70.         transition: all 0.3s;  
  71.         cursor: pointer;  
  72.         &:hover {  
  73.             color: #ff296a;  
  74.         }  
  75.     }  
  76.     &.success {  
  77.         color: #1bc7b1;  
  78.     }  
  79.     &.fail {  
  80.         color: #ff296a;  
  81.     }  
  82.     &.info {  
  83.         color: #1593ff;  
  84.     }  
  85.     &.warn {  
  86.         color: #f89300;  
  87.     }  
  88.     &.close {  
  89.         animation: fade-out 0.3s;  
  90.     }  
  91.     }  
  92. </style> 

在这里需要注意,我们定义了一个close方法,但内容是空的,虽然在模板上有用到,但是似乎没什么意义,在后面我们要扩展组件的时候我会讲到为什么要这么做。

创建完这个组件之后,我们就可以在模板中使用了<notification type="xxx" msg="xxx" />

实现通过方法调用该通知组件

其实在实现通过方法调用之前,我们需要扩展一下这个组件,因为仅仅这些属性,并不够我们使用。在使用方法调用的时候,我们需要考虑一下几个问题:

  •  显示反馈的定位
  •  组件的出现和自动消失控制
  •  连续多次调用通知方法,如何排版多个通知

在这个前提下,我们需要扩展该组件,但是扩展的这些属性不能直接放在原组件内,因为这些可能会影响组件在模板内的使用,那怎么办呢?这时候我们就要用到Vue里面非常好用的一个API,extend,通过他去继承原组件的属性并扩展他。

来看代码

 

  1. import Notifier from './Notifier.vue'  
  2. function install(Vue) {  
  3.     VueVue.notifier = Vue.prototype.notifier = {  
  4.         success,  
  5.         fail,  
  6.         info,  
  7.         warn  
  8.     }  
  9.  
  10. function open(type, msg) {  
  11.     let UiNotifier = Vue.extend(Notifier)  
  12.     let vm = new UiNotifier({  
  13.         propsData: { type, msg },  
  14.         methods: {  
  15.             close: function () {  
  16.                 let dialog = this.$el  
  17.                 dialog.addEventListener('animationend', () => {  
  18.                     document.body.removeChild(dialog)  
  19.                     this.$destroy()  
  20.                 })  
  21.                 dialog.className = `${this.type} eqc-notifier close`  
  22.                 dialog = null  
  23.             }  
  24.         }  
  25.     }).$mount()  
  26.     document.body.appendChild(vm.$el)  
  27.  
  28. function success(msg) {  
  29.     open('success', msg)  
  30.  
  31. function fail(msg) {  
  32.     open('fail', msg)  
  33.  
  34. function info(msg) {  
  35.     open('info', msg)  
  36.  
  37. function warn(msg) {  
  38.     open('warn', msg)  
  39.  
  40. Vue.use(install)  
  41. export default install 

可以看到close方法在这里被实现了,那么为什么要在原组件上面加上那些方法的定义呢?因为需要在模板上绑定,而模板是无法extend的,只能覆盖,如果要覆盖重新实现,那扩展的意义就不是很大了。其实这里只是一个消息弹窗组件,是可以在模板中就被实现,还有插件怎么注入,大家都可以自己抉择。

同时在使用extend的时候要注意:

  •  方法和属性的定义是直接覆盖的
  •  生命周期方法类似余mixin,会合并,也就是原组件和继承之后的组件都会被调用,原组件先调用

首先通过 let UiNotifier = Vue.extend(Notifier),我们得到了一个类似于Vue的子类,接着就可以通过new UiNotifier({...options})的方式去创建Vue的实例了,同时通过该方式创建的实例,会有组件定义里面的所有属性。

在创建实例之后,vm.$mount()手动将组件挂载到DOM上面,这样我们可以不依赖Vue组件树来输出DOM片段,达到自由显示通知的效果。

扩展:

(

说一下$mount,我们也许很多项目的主文件是这样的

  1. new Vue({  
  2.     router,  
  3.     store,  
  4.     el: '#app',  
  5.     render: h => h(App)  
  6. }) 

其实el与$mount在使用效果上没有任何区别,都是为了将实例化后的vue挂载到指定的dom元素中。如果在实例化vue的时候指定el,则该vue将会渲染在此el对应的dom中,反之,若没有指定el,则vue实例会处于一种“未挂载”的状态,此时可以通过$mount来手动执行挂载。值得注意的是如果$mount没有提供参数,模板将被渲染为文档之外的的元素,并且你必须使用原生DOM API把它插入文档中,所以我上面写的你应该明白了吧!

  1. 这是$mount的一个源码片段,其实$mount的方法支持传入2个参数的,第一个是 el,它表示挂载的元素,可以是字符串,也可以是 DOM 对象,如果是字符串在浏览器环境下会调用 query 方法转换成 DOM 对象的。第二个参数是和服务端渲染相关,在浏览器环境下不需要传第二个参数。 

)

好了,我们现在其实就可以在组件中:

  1. this.notifier[state](msg)来调用了,是不是很方便? 

进阶

我们刚才实现了在Vue中通过方法来进行用户反馈的提醒,再增加一个难度:

我们vue项目中应该也遇到过这种情况,弹出一个对话框或是选择框?不但要求用方法弹出,并且能接收到对话框交互所返回的结果。

这里就不详细的分析了直接上代码说(之前的代码,用render来写的组件,懒得改了,直接拿来用...),先创建一个对话框组件---Confirm.vue。

  1. <script>  
  2.     let __this = null  
  3.     export default {  
  4.         name: 'Confirm',  
  5.         data() {  
  6.             return {  
  7.                 config: {  
  8.                     msg: '',  
  9.                     ifBtn: '',  
  10.                     top: null  
  11.                 }  
  12.             }  
  13.         },  
  14.         created() {  
  15.             __this = this  
  16.         },  
  17.         methods: {  
  18.             createBox(h) {  
  19.                 let config = {}  
  20.                 config.attrs = {  
  21.                     id: '__confirm'  
  22.                 }  
  23.                 let children = []  
  24.                 children.push(this.createContainer(h))  
  25.                 children.push(this.createBg(h))  
  26.                 return h('div', config, children)  
  27.             },  
  28.             createBg(h) {  
  29.                 return h('div', {  
  30.                     class: 'bg',  
  31.                     on: {  
  32.                         click: __this.$cancel  
  33.                     }  
  34.                 })  
  35.             },  
  36.             createContainer(h) {  
  37.                 let config = {}  
  38.                 config.class = {  
  39.                     'box-container': true  
  40.                 }  
  41.                 if (__this.config.top) {  
  42.                     config.style = {  
  43.                         'top': __this.config.top + 'px',  
  44.                         'transform': 'translate(-50%, 0)'  
  45.                     }  
  46.                 }  
  47.                 let children = []  
  48.                 children.push(this.createContentBox(h))  
  49.                 children.push(this.createClose(h))  
  50.                 if (__this.config.ifBtn) {  
  51.                     children.push(__this.createBtnBox(h))  
  52.                 }  
  53.                 return h('div', config, children)  
  54.             },  
  55.             createContentBox(h) {  
  56.                 let config = {}  
  57.                 config.class = {  
  58.                     'content-box': true  
  59.                 }  
  60.                 return h('div', config, [__this.createContent(h)])  
  61.             },  
  62.             createContent(h) {  
  63.                 let config = {}  
  64.                 config.domProps = {  
  65.                     innerHTML: __this.config.msg  
  66.                 }  
  67.                 return h('p', config)  
  68.             },  
  69.             createClose(h) {  
  70.                 return h('i', {  
  71.                     class: 'eqf-no pointer close-btn',  
  72.                     on: {  
  73.                         click: __this.$cancel  
  74.                     }  
  75.                 })  
  76.             },  
  77.             createBtnBox(h) {  
  78.                 return h(  
  79.                     'div', {  
  80.                         class: {  
  81.                             'btn-box': true  
  82.                         }  
  83.                     }, [  
  84.                         __this.createBtn(h, 'btn-cancel middle mr10', '取消', __this.$cancel),  
  85.                         __this.createBtn(h, 'btn-primary middle mr10', '确定', __this.$confirm)  
  86.                     ])  
  87.             },  
  88.             createBtn(h, styles, content, callBack) {  
  89.                 return h('button', {  
  90.                     class: styles,  
  91.                     on: {  
  92.                         click: callBack  
  93.                     }  
  94.                 }, content)  
  95.             }  
  96.         },  
  97.         render(h) {  
  98.             return this.createBox(h)  
  99.         }  
  100.     }  
  101.     </script>    
  102.     <style scoped>  
  103.     #__confirm {  
  104.         position: fixed;  
  105.         top: 0;  
  106.         left: 0;  
  107.         z-index: 10;  
  108.         width: 100%;  
  109.         height: 100%;  
  110.     }  
  111.     #__confirm .bg {  
  112.         position: fixed;  
  113.         top: 0;  
  114.         left: 0;  
  115.         z-index: 0;  
  116.         width: 100%;  
  117.         height: 100%;  
  118.     }  
  119.     #__confirm .box-container {  
  120.         position: absolute;  
  121.         width: 500px;  
  122.         padding: 20px;  
  123.         padding-top: 30px;  
  124.         border-radius: 3px;  
  125.         background: #fff;  
  126.         z-index: 1;  
  127.         box-shadow: 2px 2px 10px rgba(0,0,0,0.4);  
  128.         top: 50%;  
  129.         left: 50%;  
  130.         transform: translate(-50%, -50%);  
  131.     }  
  132.     #__confirm .content-box {  
  133.         font-size: 14px;  
  134.         line-height: 20px;  
  135.         margin-bottom: 10px;  
  136.     }  
  137.     #__confirm .btn-box {  
  138.         margin-top: 20px;  
  139.         text-align: right;  
  140.     }  
  141.     #__confirm .close-btn {  
  142.         position: absolute;  
  143.         top: 15px;  
  144.         right: 20px;  
  145.         font-size: 16px;  
  146.         color: #666666;  
  147.     }  
  148.     #__confirm .close-btn:hover {  
  149.         color: #1593FF;  
  150.     }  
  151.         #__confirm .bg {  
  152.             position: fixed;  
  153.         }  
  154.     </style> 

然后创建confirm.js:

  1. 'use strict'  
  2. import Confirm from './Confirm.vue'  
  3. const confirmConstructor = Vue.extend(Confirm)  
  4. const ConfirmViewStyle = config => {  
  5.     const confirmInstance = new confirmConstructor({  
  6.         data() {  
  7.             return {  
  8.                 config  
  9.             }  
  10.         }  
  11.     })  
  12.     confirmInstanceconfirmInstance.vm = confirmInstance.$mount()  
  13.     confirmInstanceconfirmInstance.dom = confirmInstance.vm.$el  
  14.     document.body.appendChild(confirmInstance.dom)  
  15.  
  16. const close = () => {  
  17.     let dom = document.querySelector('body .modelServe-container')  
  18.     dom && dom.remove()  
  19.     Vue.prototype.$receive = null  
  20.  
  21. const closeConfirm = () => {  
  22.     let dom = document.getElementById('__confirm')  
  23.     dom && dom.remove()  
  24.     Vue.prototype.$confirm = null  
  25.  
  26. function install(Vue) {  
  27.     Vue.prototype.modelServe = {  
  28.         confirm: (obj) => {  
  29.             return new Promise(resolve => {  
  30.                 Vue.prototype.$confirm = (data) => {  
  31.                     resolve(data)  
  32.                     closeConfirm()  
  33.                 }  
  34.                 ConfirmViewStyle(obj)  
  35.             })  
  36.         }  
  37.     }  
  38.     Vue.prototype.$dismiss = close  
  39.     Vue.prototype.$cancel = closeConfirm  
  40.  
  41. Vue.use(install)  
  42. export default install 

思路很简单,在我们创建的时候同时返回一个promise,同时将resolve通行证暴露给vue的一个全局方法也就是将控制权暴露给外部,这样我们就可以向这样,我上面的confiram.vue是直接把取消绑定成了$cancel,把确定绑定成了$confirm,所以点击确定会进入full,也就是.then中,当然你也可以传参数。

 

  1. this.modelServe.confirm({  
  2.     msg: '返回后数据不会被保存,确认?',  
  3.     ifBtn: true  
  4. }).then(_ => {  
  5.     this.goBack()  
  6. }).catch()  

写的有点多,其实还可以扩展出好多技巧,比如模态框中传一个完整的组件,并展示出来,简单地写一下,其实只需改动一点。

 

  1. import Model from './Model.vue'  
  2. const modelConstructor = Vue.extend(Model)  
  3. const modelViewStyle = (obj) => {  
  4. let component = obj.component  
  5. const modelViewInstance = new modelConstructor({  
  6.     data() {  
  7.         return {  
  8.             disabledClick: obj.stopClick // 是否禁止点击遮罩层关闭  
  9.         }  
  10.     }  
  11. })  
  12. let app = document.getElementById('container')  
  13. modelViewInstancemodelViewInstance.vm = modelViewInstance.$mount()  
  14. modelViewInstancemodelViewInstance.dom = modelViewInstance.vm.$el  
  15. app.appendChild(modelViewInstance.dom)  
  16. new Vue({  
  17.     el: '#__model__',  
  18.     mixins: [component],  
  19.     data() {  
  20.         return {  
  21.             serveObj: obj.obj  
  22.         }  
  23.     }  
  24. })  
  25.  
  26. ...  
  27. Vue.prototype.modelServe = {  
  28.     open: (obj) => {  
  29.         return new Promise(resolve => {  
  30.             modelViewStyle(obj, resolve)  
  31.             Vue.prototype.$receive = (data) => {  
  32.                 resolve(data)  
  33.                 close()  
  34.             }  
  35.         })  
  36.     }  

调用:

  1. sendCallBack() {  
  2.     this.modelServe.open({  
  3.         component: AddCallback,  
  4.         stopClick: true  
  5.     }).then(data =>   
  6.         if (data === 1) {  
  7.             this.addInit()  
  8.         } else {  
  9.             this.goBack()  
  10.         }  
  11.     }) 

},

这里我们用了mixins,最后最后再简单地介绍一下mixins,extend,extends的区别。

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

  •     mixins 选项接受一个混入对象的数组。这些混入实例对象可以像正常的实例对象一样包含选项,他们将在 Vue.extend() 里最终选择使用相同的选项合并逻辑合并。举例:如果你的混入包含一个钩子而创建组件本身也有一个,两个函数将被调用。Mixin 钩子按照传入顺序依次调用,并在调用组件自身的钩子之前被调用。

注意(data混入组件数据优先钩子函数将混合为一个数组,混入对象的钩子将在组件自身钩子之前调用,值为对象的选项,例如 methods, components 和 directives,将被混合为同一个对象。两个对象键名冲突时,取组件对象的键值对。)

  •     extends 允许声明扩展另一个组件(可以是一个简单的选项对象或构造函数),而无需使用 Vue.extend。这主要是为了便于扩展单文件组件。这和 mixins 类似。**

概括

  1. extend用于创建vue实例  
  2. mixins可以混入多个mixin,extends只能继承一个  
  3. mixins类似于面向切面的编程(AOP),extends类似于面向对象的编程  
  4. 优先级Vue.extend>extends>mixins 

总结

到这里,关于如何实现通过方法调用一个Vue组件内容以及用到的一些API以及原理就差不多了,代码如有不懂得地方可以随时提问,欢迎交流。

 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2023-09-01 18:20:43

Chrome代码测试版

2011-07-27 12:58:43

Android MarAndroid应用商店

2009-03-17 09:54:46

Windows 7微软测试

2019-03-22 10:20:39

加速Windows 10启动

2020-12-10 20:00:04

数字货币比特币区块链

2011-07-29 15:02:22

LifeSize视频协作

2015-06-18 14:11:29

飞康OpenStackFreeStor

2013-11-01 16:46:31

Chrome浏览器

2017-09-18 15:04:11

VMwareNSX容器

2023-11-14 18:04:26

SQL语句性能

2015-12-22 12:00:05

SDN云服务

2012-06-14 15:50:20

teradata商业洞察数据仓库

2009-11-30 18:35:05

BizSparkDreamSparkWebSiteSpar

2014-01-08 10:22:28

思科Videoscape

2015-10-19 14:57:51

2009-12-28 10:08:07

OracleSQLDevelope开发框架

2010-03-15 09:40:19

Windows 8研发

2009-08-26 14:48:05

C#委托与事件

2011-11-10 19:44:08

思科腾讯通通信

2013-06-17 11:53:49

思科云服务思科
点赞
收藏

51CTO技术栈公众号