Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview knowledge points of Vue

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the interview knowledge points of Vue". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the interview points of Vue?"

To get to the point, I believe that almost any project will have an essential function, which is user action feedback, or reminders, like this (a simple demo).

In fact, in vue's medium-and large-scale projects, these similar small functions will be richer and more rigorous, while in front-end projects with Vue as the core framework, because Vue itself is a component-based and virtual Dom framework, it is of course very simple to achieve a notification component display. However, because of the use of notification components, it is obviously very inconvenient to write components directly in the template and control the display of notification components through v-show or props, and this means that your code structure has to change. When there are many kinds of layers, it is obviously not reasonable for us to mount them to APP or a component, and if you want to use notifications in action or other non-component scenarios Then the use of pure component mode cannot be realized. So is there any way to use the Vue component feature to easily achieve the display of a notification component, so can we use a method to control the display and hiding of the bomb layer components?

Goal one

Implement a simple feedback notification that can be called directly within the component through the method. For example, Vue.$confirm ({... obj})

First of all, let's implement the notification component. I believe that most people can write a decent component, don't talk about it, and go straight to the code:

{{msg}} export default {name: 'Notification', props: {type: {type: String, default:''}, msg: {type: String, default:''}} Computed: {iconClass () {switch (this.type) {case 'success': return' eqf-info-f' case 'fail': return' eqf-no-f' case 'info': Return 'eqf-info-f' case' warn': return 'eqf-alert-f'} Mounted () {setTimeout (() = > this.close (), 4000)}, methods: {close () {}}. Eqc-notifier {position: fixed Top: 68px; left: 50%; height: 36px; padding-right: 10px; line-height: 36px; box-shadow: 00 16px 0 rgba (0,0,0,0.16); border-radius: 3px; background: # fff; z-index: 100; / / highest level transform: translateX (- 50%) Animation: fade-in 0.3s; .icon {margin: 10px; font-size: 16px;} .close {margin: 8px; font-size: 20px; color: # 666; transition: all 0.3s; cursor: pointer; &: hover {color: # ff296a } & .success {color: # 1bc7b1;} & .fail {color: # ff296a;} & .info {color: # 1593ff;} & .success {color: # f89300;} & .close {animation: fade-out 0.3s;}

It's important to note here that we define a close method, but the content is empty, which is useful in templates, but it doesn't seem to make much sense, and I'll talk about why we're going to extend the component later.

After we have created this component, we can use it in the template

Implement to call the notification component through the method

In fact, before implementing through the method call, we need to extend this component, because these properties alone are not enough for us to use. When using method calls, we need to consider a few issues:

Display the location of the feedback

Emergence and automatic disappearance control of components

Call the notification method several times in a row, and how to type multiple notifications

Under this premise, we need to extend the component, but these extended properties cannot be placed directly in the original component, because these may affect the use of the component in the template. At this point, we will use a very useful API,extend in Vue to inherit the properties of the original component and extend it.

Look at the code.

Import Notifier from'. / Notifier.vue' function install (Vue) {VueVue.notifier = Vue.prototype.notifier = {success, fail, info, warn}} function open (type, msg) {let UiNotifier = Vue.extend (Notifier) let vm = new UiNotifier ({propsData: {type, msg}) Methods: {close: function () {let dialog = this.$el dialog.addEventListener ('animationend' () = > {document.body.removeChild (dialog) this.$destroy ()}) dialog.className = `$ {this.type} eqc-notifier close` dialog = null}). $mount () document.body.appendChild (vm.$el) )} function success (msg) {open ('success') Msg)} function fail (msg) {open ('fail', msg)} function info (msg) {open (' info', msg)} function warn (msg) {open ('warn', msg)} Vue.use (install) export default install

You can see that the close method is implemented here, so why add the definition of those methods to the original component? Because you need to bind on the template, and the template can not be extend, can only be overwritten, if you want to overwrite the re-implementation, then the meaning of the extension is not very great. In fact, this is just a message pop-up component, which can be implemented in the template, and how to inject plug-ins, everyone can make their own choices.

At the same time, when using extend, you should pay attention to:

The definitions of methods and properties are directly overridden

The lifecycle method, similar to the remaining mixin, will be merged, that is, both the original component and the inherited component will be called, and the original component will be called first.

First of all, through let UiNotifier = Vue.extend (Notifier), we get a subclass similar to Vue, and then we can create an instance of Vue through new UiNotifier ({... options}). At the same time, the instance created in this way will have all the properties in the component definition.

After creating the instance, vm.$mount () manually mounts the component to the DOM, so that we can output DOM fragments without relying on the Vue component tree to achieve the effect of free display of notifications.

Extend:

(

Speaking of $mount, we may have a lot of projects with master files like this.

New Vue ({router, store, el:'# app', render: h = > h (App)})

In fact, there is no difference between el and $mount in the effect of use, which is to mount the instantiated vue into the specified dom element. If you specify el when instantiating a vue, the vue will be rendered in the dom corresponding to the el. On the contrary, if no el is specified, the vue instance will be in an "unmounted" state, and the mount can be performed manually through $mount. It is worth noting that if $mount does not provide parameters, the template will be rendered as an element outside the document, and you must insert it into the document using native DOM API, so you should understand what I wrote above!

This is a source code snippet of $mount. In fact, the method of $mount supports passing in two parameters, the first is el, which represents the mounted element, which can be a string or a DOM object. If it is a string, it will be converted into a DOM object by calling the query method in the browser environment. The second parameter is related to server rendering. There is no need to pass the second parameter in the browser environment.

)

Well, we can actually put it in the component right now:

This.notifier [state] (msg) is called, isn't it convenient?

Advanced level

We have just implemented the reminder of user feedback in Vue, which adds one more difficulty:

We should have encountered this situation in our vue project, popping up a dialog box or a selection box? It is required not only to pop up with the method, but also to receive the results returned by the dialog box interaction.

Here is not a detailed analysis of the direct code to say (the previous code, components written in render, too lazy to change, directly use.), first create a dialog box component-Confirm.vue.

Let _ _ this = null export default {name: 'Confirm', data () {return {config: {msg:', ifBtn:'', top: null} Created () {_ _ this = this} Methods: {createBox (h) {let config = {} config.attrs = {id:'_ confirm'} let children = [] children.push (this.createContainer (h)) Children.push (this.createBg (h)) return h ('div') Config, children)}, createBg (h) {return h ('div', {class:' bg', on: {click: _ _ this.$cancel}})} CreateContainer (h) {let config = {} config.class = {'box-container': true} if (_ _ this.config.top) {config.style = {' Top': _ _ this.config.top + 'px' 'transform':' translate (- 50%) 0)'}} let children = [] children.push (this.createContentBox (h)) children.push (this.createClose (h)) if (_ _ this.config.ifBtn) {children.push (_ this.createBtnBox) (h))} return h ('div' Config, children)}, createContentBox (h) {let config = {} config.class = {'content-box': true} return h (' div', config, [_ _ this.createContent (h)])} CreateContent (h) {let config = {} config.domProps = {innerHTML: _ _ this.config.msg} return h ('paired, config)}, createClose (h) {return h (' i') {class: 'eqf-no pointer close-btn', on: {click: _ _ this.$cancel}})} CreateBtnBox (h) {return h ('div', {class: {' btn-box': true}}, [_ _ this.createBtn (h) 'btn-cancel middle mr10',' cancel', _ _ this.$cancel), _ _ this.createBtn (h, 'btn-primary middle mr10',' OK', _ _ this.$confirm)])}, createBtn (h, styles, content, callBack) {return h ('button') {class: styles, on: {click: callBack}}, content)}} Render (h) {return this.createBox (h)} # _ _ confirm {position: fixed Top: 0; left: 0; z-index: 10; width: 100%; height: 100%;} # _ confirm .bg {position: fixed; top: 0; left: 0; z-index: 0; width: 100%; height: 100% } # _ confirm. Box-container {position: absolute; width: 500px; padding: 20px; padding-top: 30px; border-radius: 3px; background: # fff; z-index: 1; box-shadow: 2px 2px 10px rgba Transform: translate (- 50%,-50%);} # _ confirm. Content-box {font-size: 14px; line-height: 20px; margin-bottom: 10px;} # _ confirm. Btn-box {margin-top: 20px; text-align: right;} # _ confirm. Close-btn {position: absolute Top: 15px; right: 20px; font-size: 16px; color: # 666666;} # _ confirm. Close-btn:hover {color: # 1593FF;} # _ confirm .bg {position: fixed;}

Then create the confirm.js:

'use strict' import Confirm from'. / Confirm.vue' const confirmConstructor = Vue.extend (Confirm) const ConfirmViewStyle = config = > {const confirmInstance = new confirmConstructor ({data () {return {config}) confirmInstanceconfirmInstance.vm = confirmInstance.$mount () confirmInstanceconfirmInstance.dom = confirmInstance.vm.$el document.body. AppendChild (confirmInstance.dom)} const close = () = > {let dom = document.querySelector ('body. ModelServe-container') dom & & dom.remove () Vue.prototype.$receive = null} const closeConfirm = () = > {let dom = document.getElementById (' _ confirm') dom & & dom.remove () Vue.prototype.$confirm = null} function install (Vue) {Vue.prototype.modelServe = {confirm: (obj) = > {return new Promise (resolve = > {Vue.prototype.$confirm = (data) = > {resolve (data) closeConfirm ()} ConfirmViewStyle (obj)})}} Vue.prototype.$dismiss = close Vue.prototype.$cancel = closeConfirm} Vue.use (install) export default install

The idea is simple: a global way to return a promise when we create and expose the resolve pass to the vue is to expose the control to the outside, so we can do this. The confiram.vue above me directly unbinds the unbinding to $cancel and binds the confirmation to $confirm, so clicking OK will enter the full, that is, .then, of course, you can also pass parameters.

This.modelServe.confirm ({msg: 'data will not be saved after return, confirm?', ifBtn: true}) .then (_ = > {this.goBack ()}) .catch ()

Write a little too much, in fact, you can also expand a lot of skills, such as the modal box to transfer a complete component, and show it, simply write, in fact, only need to change a little.

Import Model from'. / Model.vue' const modelConstructor = Vue.extend (Model) const modelViewStyle = (obj) = > {let component = obj.component const modelViewInstance = new modelConstructor ({data () {return {disabledClick: obj.stopClick / / whether to disable clicking on the mask layer to close}) let app = document.getElementById ('container') modelViewInstancemodelViewInstance.vm = modelViewInstance.$mount () ModelViewInstancemodelViewInstance.dom = modelViewInstance.vm.$el app.appendChild (modelViewInstance.dom) new Vue ({el:'# _ _ model__' Mixins: [component], data () {return {serveObj: obj.obj}})}. Vue.prototype.modelServe = {open: (obj) = > {return new Promise (resolve = > {modelViewStyle (obj, resolve) Vue.prototype.$receive = (data) = > {resolve (data) close ()}})}}

Call:

SendCallBack () {this.modelServe.open ({component: AddCallback, stopClick: true}) .then (data = > if (data = 1) {this.addInit ()} else {this.goBack ()})

}

Here we use mixins, and finally we briefly introduce the differences between mixins,extend,extends.

* *-Vue.extend uses the underlying Vue constructor to create a "subclass". Parameter is an object that contains component options.

The mixins option accepts an array of mixed objects. These mixed instance objects can contain options like normal instance objects, and they will eventually choose to merge logically using the same options in Vue.extend (). For example: if your mix contains a hook and the creation component itself has one, two functions will be called. The Mixin hook is called in the incoming order and is called before calling the component's own hook.

Note (the data blending component data priority hook function will be mixed into an array, the hook mixed with the object will be called before the component's own hook, and options with values of object, such as methods, components, and directives, will be mixed into the same object. When the key names of two objects conflict, take the key-value pair of the component object.)

Extends allows declarations to extend another component (which can be a simple option object or constructor) without using Vue.extend. This is mainly to facilitate the expansion of single-file components. This is similar to mixins. **

Generalization

Extend is used to create vue instances mixins can be mixed with multiple mixin,extends can only inherit one mixins similar to aspect-oriented programming (AOP), extends is similar to object-oriented programming priority Vue.extend > extends > mixins so far, I believe you have a deeper understanding of "what are the interview knowledge points of Vue", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report