preface

Use this article to summarize the Vue preliminary interview questions.

What is MVVM

  • MVVM stands for model-view-ViewModel.
  • The Model represents the data Model, where you can also define the business logic that operates on data changes;
  • View represents the UI View, which is responsible for converting the data model into a UI for presentation;
  • The ViewModel listens for changes in the Model and controls the presentation of the View layer.
  • In MVVM architecture, there is no direct connection between View and Model, but interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, so the changes of View data are synchronized to Model. Changes to Model data are immediately reflected in the View;
  • The ViewModel connects the View layer with the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic, do not need to manually manipulate DOM, do not need to pay attention to the synchronization of data state. Complex data state maintenance is managed entirely by MVVM.

What are the hook functions

  • beforeCreate: called before instance creation;
  • created: the instance is called after creation, completes data observation, property and method calculation, watch/event event callback, and template rendering into HTML (vm.$el not defined) so data initialization is best done in this stage;
  • beforeMountIn:$elCalled before mount, the associated render function is called for the first time during which the module is rendered to HTMLvm.$elIt’s still undefined;
  • mountedIn:$elAfter mount is called at this timevm.$elCan be called, can not guarantee that all the child components are mounted, until the view is fully updatedvm.$nextTick();
  • beforeUpdate: called when data is updated;
  • updated: called after data update;
  • activated:<keep-alive></keep-alive>Called when the wrapped component is activated;
  • deactivated:<keep-alive></keep-alive>Called when the wrapped component leaves;
  • beforeDestroy: called before instance destruction, when the instance is still fully available;
  • destroyed: called after the instance is destroyed, at which point everything in the instance is unbound, all event listeners are removed, and all subinstances are destroyed.

What are the instance methods of the life cycle

  • vm.$mount()To return tovm, can chain call other instance methods;(not often used)
    const myVue = Vue.extend({ template: '<div>Hello! </div>'}) new myVue().$mount('#warp') // render outside the document and then mount($mount without parameters) const Component = new myVue().$mount() document.getElementById('app').appendChild(component.$el)Copy the code
  • vm.$forceUpdate()Forcing the Vue instance to re-render, not reloading the component, triggers beforeUpdate and updated hook functions and does not trigger other hook functions. It affects only the instance itself and the children that insert slot content, not all children;
  • vm.$nextTick()The callback function’s this is automatically bound to the instance calling it.
  • vm.$destroy()To destroy an instance. Cleans up its connection to other instances, unties all instructions and event listeners, but does not clean up the DOM and data of the instance, and triggers beforeDestroy and Destroyed hook functions.

Four, vUE has what instructions, a brief introduction, at least say 10

  • V-else -if must be used with v-if;

  • V-else must be used with v-if;

  • V -for, loop render elements or components with Array, Object, Number, and String data. Render components must carry keys, which must be specified for each item in the data, such as ID;

    <div v-for="(item,index) in Array">{{index}}-{{item}}</div>
    <div v-for="(item,key,index) in Object">{{index}}-{{key}}--{{item}}</div>
    <div v-for="item in Number">{{item}}</div>
    <div v-for="(item,index) in String">{{index}}-{{item}}</div>
    <myVue v-for="(item,key,index) in Object" :title="item.title" :key="item.id"></myVue>
    Copy the code
  • V-on, abbreviated @, listens for events such as @click, @submit, and @dblclick

    • How do I get the position of the mouse click on div
      < div @ click = "a" > < / div > < div @ click = "b (1, 2, $event)" > < / div > the methods: {a () {the console. The log (event. ClientX, event. ClientY)}, b(num1,num2,$event){ console.log($event.clientX,$event.clientY) }, }Copy the code
    • How do I prevent bubbling, how do I prevent default events
      / / stop the bubbling < div @. Click the stop = "a" > < / div > / / stop the default < div @ click. Prevent = "b" > < / div > / / stop the bubbling stop default < div @ click. Stop. Prevent = "c" > < / div >Copy the code
    • How do I listen for native events on the component root element
      <myVue @click.native="d"></myVue>
      Copy the code
    • How do I listen for component custom events
      $emit('diyEvent',data) <myVue @diy-event="f">Copy the code
  • V-bind, abbreviated: bind dynamic properties;

  • V-model, which restricts the application of bidirectional bindings on < INPUT >

    Without saying these 8 very common instructions, it’s time to stop interviewing

  • V – text, < div v – text = “data” > < / div > equivalent < div > {{data}} < / div >.

  • V-html, output HTML directly, will not be compiled according to Vue template, there will be XSS attack analysis, do not use in user submitted content;

  • V-once, which renders elements and components only once. In subsequent re-rendering, the element/component and all its child nodes are treated as static and skipped to optimize update performance;

  • V-per, skips compilation of this element and its children. You can use it to display the original Mustache tag. Skipping a large number of nodes without instructions speeds up compilation;

  • [v-cloak] {display: None} is needed at the time of page loading.

  • V-slot, detailed in component slots.

How to monitor data changes

data(){ return(){ a:{ b:{ c:1, d:2 } } e:'dfe' } }, watch:{ a:{ handler:function(val,oldVal){}, deep:true }, 'handler ':{handler:function(val,oldVal){}, deep:true}, d: {handler: 'handlewacthD', immediate: true }, }, methods:{ handlewacthD(val,oldVal){} }Copy the code

6. Calculate attributes

This question must be asked, which is related to the later maintenance, if you are not familiar with this, then he may write too much logical calculation in the interpolation, leading to the template is not concise will lead to the later maintenance difficulties, will think of whether the person pays attention to the simplicity of the code and maintenance.

  • Why use computed properties?

    A: Avoid putting too much logic into a template that is too heavy and difficult to maintain.

  • What are the properties of calculated properties?

    A: Computed properties are cached based on their reactive dependencies, and they are reevaluated only when the associated reactive dependencies change.

  • Calculate what getters and setters for properties are and what they do.

    A:

    < the template > < div > < span > {{a}} < / span > < span > and < / span > < span > {{b}} < / span > < span > is < / span > < span > {{c}} < / span > < span > {{a}} < / span > < span > by < / span > < span > {{b}} < / span > < span > to < / span > < span > {{d}} < / span > < button @ click = "add" > 1 < / button > </div> </template> <script> export default { data() { return { a: 1, b: 2 }; }, computed: { c: function() { return this.a + this.b; }, d: { get: function() { return this.a * this.b; }, set: function(val) { this.a = val/this.b; } } }, methods: { add(){ this.d=this.d*2; }}}; </script>Copy the code

How to bind Class and Style dynamically

  • Div (test, active, active-click)<div class="test active active-click"></div>While test is fixed, active is controlled by actived and clicked from data. Active-click is controlled by actived and clicked from data.
    template> <div> <! <div class="test" :class="{active: actived, 'active-click': clicked && actived}"></div> <! <div class="test" :class=" clicked ", clicked && Actived? ActiveClickClass: '' ]"></div> <! <div :class="[testClass, {active: actived}, {'active-click': clicked && actived}]"></div> <! --> <div :class="classObject"></div> </div> </template> <script> export default {data() {return { actived: true, clicked: true, testClass: 'test', activeClass: 'active', activeClickClass: 'active-click', } }, computed: { classObject: function() { return { test: true, active: this.actived, 'active-click': this.actived && this.clicked, } } }, } </script>Copy the code
  • Click on the word “test”, the font color will change to red, font size to 14px, font bold, click again, the font color will change to black, font size to 12px, font bold, use the dynamic binding Style method to implement, two dynamic binding Style writing methods.
    <template> <div> <span @click="handleClick" :style="{ color:color, fontSize:fontSize, <span @click="handleClick" :style="[styleObject]"> </span @click="handleClick" :style="styleObject"> Test </span> </div> </template> <script> export default {data() {return { color: '#000', fontSize:'12px', fontWeight: 'normal', } }, computed: { styleObject:function(){ return { color: this.color, fontSize:this.fontSize, fontWeight: this.fontWeight, } } }, methods:{ handleClick(){ this.color = this.color=='#000'? 'red' : '#000'; this.fontSize = this.fontSize=="12px"? '14px' : '12px'; this.fontWeight=this.fontWeight='normal'? 'bold' :'normal'; } } } </script>Copy the code

Which of the methods used to manipulate data arrays in Vue can trigger view update, which can not, if not, what is the solution?

Push (), pop(), shift(), unshift(), splice(), sort(), reverse() change the array being manipulated; The filter(), concat(), and slice() methods do not alter the array being operated on, but return a new array; All of the above methods can trigger view updates.

  • Set an array item directly using an index, for example: this.array[index] = newValue

  • Change the length of the array, for example, this.array.length = newLength

The above two methods cannot trigger view updates;

  • Can use this. $set (this array, index, newValue) or enclosing array. The splice (index, 1, newValue) solution 1

  • You can use this.array.splice(newLength) solution 2

9. How to add or delete attributes to objects in data to trigger view updates

Due to JavaScript limitations, Vue cannot detect the addition or deletion of object attributes,

Const vm = new Vue ({el: '# app, data: {a: {b: 1, 2: c, e, {f: 3}}}}) / / Vue is can't detect a object update vm. A. d. = 3; // Vue cannot detect the update of a delete a.c; $set(this. A, d, 3); vm.$set(this.a.e, f, 4); vm.$set(this.a, e, {g:5}); this.a=Object.assign({}, this.a, {d:3}); vm.$delete(this.a, 'c');Copy the code

Can v-for and V-if be used together?

Yes, but it depends on the application scenario, for example

Since v-for has a higher priority than V-IF on the same node, v-IF will run separately in each V-for loop. This can be used if you want to implement rendering of li nodes that meet the criteria

<ul>
    <li v-for="item in items" v-if="item.show">{{item}}</li>
</ul>
Copy the code

This should be done if you want to implement execution that conditionally skips the loop

<ul v-if="items.length">
    <li v-for="item in items">{{item}}</li>
</ul>
Copy the code

11. Blend in

  • How is global interfuse used in projects?

    Write to main.js

        import Vue from 'vue';
        import mixins from './mixins';
        Vue.mixin(mixins);
    Copy the code

    After that, global mixins can be written in the mixins folder index.js, and global mixins will affect every Vue instance (component) created after that.

  • How are local blends used in projects

    Create a a_mixin.js file in the mixins file and then write to the a.ue file

    <script>
        import aMixin from 'mixins/a_mixin'
        export default{
            mixins:[aMixin],
        }
    </script>
    Copy the code

    Local mixing will only affect Vue instances created in a. Vue files, not Vue instances created by its children.

  • How are component options and mixin options combined

    • Data object [data option], internal recursive merge, and in case of conflict with component data precedence;

    • The hook function of the same name will be merged into an array, so both will be called. In addition, hooks mixed with objects are called before the component’s own hooks;

    • When the watch object is merged, the same key is synthesized into an object, and the mixin listener is called before the component listens.

    • The filters, computed, Methods, Components, and directives options that are values for the object will be combined into the same object. When two object key names conflict, the component object’s key-value pair is taken.

Xii. Filter

  • RMB exchange rate conversion function with a local filter, support USD (0.15 exchange rate), Sterling (0.12 exchange rate)

    < template > < div > < input v - model = "money" type = "number" / > the < div > < span > {{money | moneyFilter (0.15)}} $< / span > < / div > < div > < span > {{money | moneyFilter (0.12)}} < / span > m < / div > < / div > < / template > < script > export default {data () {return { money: 1 }; }, filters: { moneyFilter: function(val, ratio) { return Number(val * ratio).toFixed(2); }}}; </script>Copy the code
  • Can an interpolation use two filters in succession?

    Can, {{message | filterA | filterB}}

  • Where else can filters be used besides interpolation?

    Can also v – bind expression, such as: < div: id = “rawId | formatId” > < / div >

How do parent and child components communicate

  • Parent component to child component communication props.

    /* Parent component */ <template> <child :title="childTitle"></child> </template> <script> export default {data() {return { ChildTitle: 'Child component title'}; }}; </script>Copy the code
    /* subcomponent */ <template> <h2>{{title}}</h2> </template> <script> export default {props:['title'], data() {return {}; }}; </script>Copy the code

    The parent component renders the < H2 > child component’s title

  • Child component to parent component communication via custom events in parent component and this.$emit(‘ parent custom event ‘,’ data to be sent to parent component ‘) in child component.

    /* Parent component / <template> <child :title="childTitle" @set-title="setTitle"></child> </template> <script> export default { Data () {return {childTitle: "Child component title"}; }, methods:{ setTitle(data){ this.childTitle=data; }}}; </script>Copy the code
    /* subcomponent */ <template> <h2 @click="changeTitle">{{title}}</h2> </template> <script> export default {props:['title'] data() { return {}; }, methods:{changeTitle(){this.$emit('set-title',' I want to change the title')}}; </script>Copy the code

conclusion

The 13 interview questions summarized above are suitable for Vue junior engineers who are capable of business development in an environment where the project leader has established the existing framework and template. In our company, the above questions must be answered correctly at least 10 times before being considered for employment.

subsequent

  • Vue Interview questions
  • Vue intermediate interview questions
  • Vue Advanced Interview questions summary