preface

The e front end of the market now, has not compared with a few years ago, a few years ago front-end interview as long as you know JQ, but now the front end of the interview has developed to source level. We are helpless, but we can not change it, so since we can not change it, we have to adapt to it and improve ourselves. Opportunities are reserved for those who are prepared. A few days ago, I chatted with a friend for a while, and found that many of his mainstream VUE knowledge are recalculate, but is asked about some non-mainstream unpopular VUE knowledge, he can not answer most departments. So today I sorted out fifteen Vue’s obscure knowledge, of course, I also hope that this is just my personal obscure knowledge, after all, I still hope that every student is a great god ha ha ha!!

If you like my article, please help me point like it, thank you!!

1. What happens if the child component changes the data in the props

1.1 The props data to be changed is the basic type

If the basic type is modified, an error is reported

props: {
    num: Number,}created() {
    this.num = 999
  }
Copy the code

The props data changed in 1.2 is a reference type

props: {
    item: {
      default: () = >{},}}created() {
    // No error is reported, and the parent data changes accordingly
    this.item.name = 'sanxin';
    
    // An error will be reported, just as an error will be reported for the base type
    this.item = 'sss'
  },
Copy the code

2. How to customize validation for props

props: {
    num: {
      default: 1.validator: function (value) {
          // If the return value is true, the validation fails
          return [
            1.2.3.4.5].indexOf(value) ! = = -1}}}Copy the code

3. What is the use of the Immediate attribute on watch?

For example, if we request the data once when created, and request the data when the search value changes, we would write:

created(){
  this.getList()
},
watch: {
  searchInputValue(){
    this.getList()
  }
}
Copy the code

You can write this completely with immediate. When it is true, it is initially executed

watch: {
  searchInputValue: {handler: 'getList'.immediate: true}}Copy the code

4. How to exclude certain properties when watching an object

If params changes, the data will be rerequested, whether the a, B, C, or D attributes change

data() {
    return {
      params: {
        a: 1.b: 2.c: 3.d: 4}}; },watch: {
    params: {
      deep: true.handler() {
        this.getList; }},}Copy the code

But what if I just want to ask again when A, B changes, and not ask again when C, D changes?

mounted() {
    Object.keys(this.params)
      .filter((_) = >! ["c"."d"].includes(_)) // Exclude listening for c, d attributes
      .forEach((_) = > {
        this.$watch((vm) = > vm.params[_], handler, {
          deep: true}); }); },data() {
    return {
      params: {
        a: 1.b: 2.c: 3.d: 4}}; },watch: {
    params: {
      deep: true.handler() {
        this.getList; }},}Copy the code

5. What is data-V-xxXXX when reviewing elements?

This is caused by using the scoped tag when marking CSS in a vue file. To ensure that the CSS in each file does not interact with each other, each component is marked uniquely, so that each component is introduced with a new ‘data-v-xxx’ tag

6. For computed, how can I implement parameter transmission?

// html
<div>{{ total(3)}}// js
computed: {
    total() {
      return function(n) {
          return n * this.num
         }
    },
  }

Copy the code

7. Use of Vue’s hook

7.1 Used in the same Component

This is how we usually use timers

export default{
  data(){
    timer:null  
  },
  mounted(){
      this.timer = setInterval(() = >{
      // The details of the implementation
      console.log('1');
    },1000);
  }
  beforeDestory(){
    clearInterval(this.timer);
    this.timer = null; }}Copy the code

The problem with this approach is that you need to define an additional timer variable globally. You can use hook to do this:

export default{
  methods: {fn(){
      const timer = setInterval(() = >{
        // Execute the code
        console.log('1');
      },1000);
      this.$once('hook:beforeDestroy'.() = >{
        clearInterval(timer);
        timer = null; })}}}Copy the code

7.2 Use of parent and child Components

If a child component wants to fire a function of its parent component when mounted, it would normally write:

/ / the parent component
<rl-child @childMounted="childMountedHandle"
/>
method () {
  childMountedHandle() {
  // do something...}},/ / child component
mounted () {
  this.$emit('childMounted')},Copy the code

It is more convenient to use hook:

/ / the parent component
<rl-child @hook:mounted="childMountedHandle"
/>
method () {
  childMountedHandle() {
  // do something...}},Copy the code

8. Are provide and inject responsive?

// The ancestor component
provide(){
    return {
   // keyName: {name: this.name}, // value is an object to implement the response, that is, the reference type
      keyName: this.changeValue // This can also be done by using a function. [Note that the function is a value, not this.changevalue ()]
   // keyName: 'test' value If it is a basic type, the response cannot be implemented}},data(){
  return {
	name:'Joe'}},methods: {
  	changeValue(){
  		this.name = 'Changed name - Lee Si'}}// The descendant component
  inject: ['keyName']
  create(){
	console.log(this.keyName) // The new name is Lisi
}
Copy the code

9.Vue’s EL attribute and $mount priority?

For example, in the following case, which node will Vue render to

new Vue({
  router,
  store,
  el: '#app'.render: h= > h(App)
}).$mount('#ggg')
Copy the code

Here is an official chart showing that when el and $mount exist together, the el priority is > $mount

10. Have dynamic commands and parameters been used?

<template>
    ...
    <aButton @[someEvent]="handleSomeEvent()" :[someProps]="1000"/ >... </template><script>.data(){
    return{...someEvent: someCondition ? "click" : "dbclick".someProps: someCondition ? "num" : "price"}},methods: {
    handleSomeEvent(){
      // handle some event}}</script>
Copy the code

11. How can the same routing component be rerendered?

Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue for performance reasons by default shared components will not be rerendered and if you try to switch between routes that use the same component nothing will change.

const routes = [
  {
    path: "/a".component: MyComponent
  },
  {
    path: "/b".component: MyComponent
  },
];
Copy the code

What if I still want to rerender? You can use keys

<template>
    <router-view :key="$route.path"></router-view>
</template>
Copy the code

12. Customize the V-Model

By default, v-Model is the syntactic sugar on the @Input event listener and the :value attribute. However, you can specify a model property in your Vue component to define what event and value properties to use — great!

export default: {
  model: {
    event: 'change'.prop: 'checked'}}Copy the code

13. How to obtain the initial state of a data in the data?

In development, it is sometimes necessary to take the initial state to calculate. For example,

data() {
    return {
      num: 10
  },
mounted() {
    this.num = 1000
  },
methods: {
    howMuch() {
        // Calculate how much num has been increased, which is 1000 - the initial value
        $options.data().xxx to get the initial value
        console.log(1000 - this.$options.data().num)
    }
  }
Copy the code

14. Why is v-for and V-IF not recommended

<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item ! = = 3">
    {{item}}
</div>
Copy the code

The above method is written as v-for and V-if exist at the same time. First, all 7 elements are traversed, and then each one is judged to be 3, and 3 is hidden. The disadvantage of this method is that useless 3 nodes are rendered and useless DOM operations are added.

<div v-for="item in list">
    {{item}}
</div>

computed() {
    list() {
        return [1.2.3.4.5.6.7].filter(item= >item ! = =3)}}Copy the code

15. Which is better, methods or computed?

<div>
    <div>{{howMuch1()}}</div>
    <div>{{howMuch2()}}</div>
    <div>{{index}}</div>
</div>

data: () {
    return {
         index: 0}}methods: {
    howMuch1() {
        return this.num + this.price
    }
  }
computed() {
    howMuch2() {
        return this.num + this.price
    }
  }
Copy the code

Computed is better because computed has caching. For example, if index changes from 0 to 1, the view will be updated and methods will be executed again, but computed will not, because the two variables on which Computed depends, num and price, will not change.

conclusion

Mainstream knowledge is important, but some unusual knowledge is also needed to know.

If you think you learned something, please give it a thumbs up! Thank you! If you want to learn about Vue source code, you can read my source code series

  • Do you want to know how Vuex works?
  • Do you really know how a Slot is “inserted”?
  • “Vue source learning (a)” you don’t know – data responsive principle
  • “Vue source learning (2)” you do not know – template compilation principles

Study group

Please click the link