Useful Vue development skills

Original link: https://juejin.im/post/5d861aabe51d4557ca7fde06

1. Status sharing

With the refinement of components, multi-component states will encounter shared, Vuex course, these problems can be solved, but as Vuex official document said, if the application is not big enough to avoid redundancy code is cumbersome, it is best Do not use it, and today we introduce a new addition vue.js 2.6 Observable API, by using this api we can deal with the situation a few simple cross-component data sharing state.

Following this example, we will create a store outside the component, and then store mutation method store.js provided App.vue components inside the same way that other components may be used as such, in order to achieve a plurality of data states shared components.

First create a store.js, comprising a store and a mutations, and are used to point to data processing method.

1 import Vue from"vue";
2 
3 export const store = Vue.observable({ count: 0 });
4 
5 export const mutations = {
6   setCount(count) {
7     store.count = count;
8   }
9 };

This store.js App.vue then introduced in the inside, and methods of using the data in the component is introduced inside the

2. The long list of performance optimization

We should all know vue will be hijacked by object.defineProperty of data to achieve response to changes in data view, but there are times when our component is pure data show, there will be no change, we do not need to hijack our vue data, in the case of large amounts of data display, which can initiate the obvious reduction in assembly time, it is how to stop vue hijack our data? You can freeze an object by object.freeze method, once frozen objects can no longer be changed

1 export default {
2   data: () => ({
3     users: {}
4   }),
5   async created() {
6     const users = await axios.get("/api/users");
7     this.users = Object.freeze(users);
8   }
9 };
Also to be noted that, here just froze value users, the reference will not be frozen, when we need reactive data, we can re-assignment to users.
. 1 Export default {
 2    Data: () => ({
 . 3      Users: {}
 . 4    }),
 . 5    the async Created () {
 . 6      const = Users the await axios.get ( "/ API / Users" );
 . 7      the this .users = Object.freeze (Users);
 . 8    },
 . 9    Methods: {
 10      // change value does not trigger the response view this.data.users [0] = newValue 
. 11      // change the view in response to the trigger reference still this.data.users = newArray 
12 is    }
 13 is };

3. Remove excess style

As more and more projects, writing not pay attention, it will produce some unnatural excess css, small projects Fortunately, once the project after the big, extra css will be more and more, resulting in more and more packages , which affect the performance of the project, it is necessary to remove these in a formal environment of excess css, here we recommend a library purgecss, support a variety of ways CLI, JavascriptApi, Webpack such as the use, through this library, we can easily get rid of excess the css.

 1 <h1>Hello Vanilla!</h1><div>
 2   We use Parcel to bundle this sandbox, you can find more info about Parcel
 3   <ahref="https://parceljs.org"target="_blank"rel="noopener noreferrer">here</a>.
 4 </div>
 5 
 6 body {
 7   font-family: sans-serif;
 8 }
 9 a {
10   color: red;
11 }
12 ul {
13   li {
14     list-style: none;
15   }
16 }
17 
18 
19 import Purgecss from"purgecss";
20 const purgecss = new Purgecss({
21   content: ["**/*.html"],
22   css: ["**/*.css"]
23 });
24 const purgecssResult = purgecss.purge();
 

PurgecssResult final result of the following, you can see a pattern of excess and ul tags gone

4. Functional assembly

Functional components, i.e. stateless, can not be instantiated, no internal lifecycle processing method is very lightweight, high performance rendering thus, particularly suitable for data transfer only rely on external components varies.

Worded as follows:

In the tag template which indicate functional value need only accept script tag props

 1 <!-- App.vue -->
 2 <template>
 3    <div id="app">
 4     <List:items="['Wonderwoman', 'Ironman']" :item-click="item => (clicked = item)"
 5     />
 6        <p>Clicked hero: {{ clicked }}</p>
 7     </div>
 8     </template>
 9 <script>
10 import List from"./List";
11 
12 exportdefault {
13   name: "App",
14   data: () => ({ clicked: "" }),
15   components: { List }
16 };
17 </script>
18 
19 <!-- List.vue 函数式组件 -->
20 <template functional>
21     <div>
22     <p v-for="item in props.items" @click="props.itemClick(item);">
23       {{ item }}
24     </p></div>
25  </template>
 

5. monitor the life cycle of components

For example, has a parent component and subassembly Parent Child, listening to the child if the parent component assembly mounted on the mount to do some processing logic, conventional wording could be as follows:

1  // Parent.vue
2 <Child @mounted="doSomething"/>
3 
4 // Child.vue
5 mounted() {
6   this.$emit("mounted");
7 }

There is provided a particularly simple manner, sub-assembly without any treatment, only when the parent component by reference to listen to @hook, code is rewritten as follows:

1 <Child @hook:mounted="doSomething"/>
2 <Child @hook:updated="doSomething"/>
Of course, this can not just listen mounted, other life cycle events, for example: created, updated and so can be, is not particularly convenient ~

Another example is the usual binding unload event:

1 window.addEventListener('resize',this.handleResize)
2 this.$on('hook:destroyed',() => {
3     window.removeventListener('resize',this.handleResize)
4 })

For more information about hooks usage (useMounted, useComputed) to view vue-hook Source

Immediate execution of the initial 6.Watch

When watch a variable, and initialization is not executed, as in the following example, you need to call a manually created when the.

1  created () {
 2    this .fetchUserList ();
3  },
 4  watch {
 5    search text: 'Fetch user list' ,
 6 }
Such practices above may be used, but a lot of trouble, we can add immediate property, so initialization time will automatically trigger (do not write created to call), then the above code can be simplified as:
1 watch: {
2   searchText: {
3     handler: 'fetchUserList',
4     immediate: true
5   }
6 }

7.Watch depth monitor

1  data () {
 2    return {
 3      search text: {
 4        date: '123'
 5      }
 6    }
 7  }
 8  watch {
 9    search text: {
 10      Handler 'Fetch user list' ,
 11      deep, true 
12    }
 13  }
 14  Methods {
 15    Fetch user list () {}
 16 }

So deep you can listen to the changes searchText.date

8 ~ bit operation rapidly converted to digital

1 let a = '12136546';
2 let b = 0;
3 
4 b = ~~a;
5 console.log(b) //12136546
6 a = 'asdsad'
7 b = ~~a;
8 console.log(b) //0

 

 

 
 

Guess you like

Origin www.cnblogs.com/ljyyjj/p/11611875.html