7 useful Vue development tips

1 Status Sharing

Vuex can solve this problem, but as Vuex official documents say, if the application is not big enough, it is better not to use it to avoid tedious code. Today we introduce the New Observable API added in Vuue. Js 2.6. Using this API we can deal with some simple sharing of data state across components.

In the following example, we will create a store outside the component and use the store and mutation methods provided by store.js in the app. vue component.

Start by creating a store.js that includes a store and mutations, which point to the data and treatment methods, respectively.

import Vue from "vue"; export const store = Vue.observable({ count: 0 }); export const mutations = { setCount(count) { store.count = count; }};Copy the code

Then import the store.js in app.vue and use the imported data and methods in the component

<template> <div id="app"> <img width="25%" src="./assets/logo.png"> <p>count:{{count}}</p> <button @click="setCount(count+1)">+1</button> <button @click="setCount(count-1)">-1</button> </div> </template> <script> import  { store, mutations } from "./store"; export default { name: "App", computed: { count() { return store.count; } }, methods: { setCount: mutations.setCount } }; </script> <style>Copy the code

You can click on the online DEMO to see the final result

Long list performance optimization

We all know that Vue hijacks data via Object.defineProperty to make the view respond to data changes. However, sometimes our component is purely a data presentation and nothing changes. We don’t need vue to hijack our data. This significantly reduces component initialization time, so how do we prevent VUE from hijacking our data? Freeze can be used to freeze an object. Once the object is frozen, it cannot be modified.

export default { data: () => ({ users: {} }), async created() { const users = await axios.get("/api/users"); this.users = Object.freeze(users); }};Copy the code

It is also important to note that the value of users is frozen and the reference is not frozen. When we need reactive data, we can re-assign values to Users.

export default { data: () => ({ users: [] }), async created() { const users = await axios.get("/api/users"); this.users = Object.freeze(users); }, methods:{this.users[0] = newValue // changing a reference will still trigger a view response this.users = newArray}};Copy the code

3. Eliminate redundant styles

As the project is more and more big, do not pay attention to writing, unnatural can produce some extra CSS, small projects well, once the project is big, the extra CSS will be more and more, lead to package more and more big, thus affecting project running performance, so it is necessary in the formal environment to get rid of these extra CSS, here recommend a repository purgecss, Support CLI, JavascriptApi, Webpack and other ways to use this library, we can easily remove redundant CSS.

I did a test, an online DEMO

<h1>Hello Vanilla! </h1> <div> We use Parcel to bundle this sandbox, you can find more info about Parcel <a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>. </div>Copy the code
body { font-family: sans-serif; } a { color: red; } ul { li { list-style: none; }}Copy the code
import Purgecss from "purgecss";
const purgecss = new Purgecss({
  content: ["**/*.html"],
  css: ["**/*.css"]
});
const purgecssResult = purgecss.purge();
Copy the code

The resulting purgecssResult is as follows, and you can see that the extra A and UL tag styles are gone

4 Scope slot

There are some interesting things that can be done with scope slots, such as defining A basic layout component (A) that only handles layout, regardless of data logic, and then defining another component (B) that handles data processing. Layout component (A) goes to B to fetch data when it needs it. Suppose, one day, our layout changes and we only need to modify component A, not component B, so that we can fully reuse the data processing logic of component B. I wrote A practical example of this before, which can be viewed here.

One of the most important points involved here is that the parent component gets data from the child component. Previously, slot-scope was used. Since VUE 2.6.0, there are better API alternatives that support slot and slot-Scope features.

For example, let’s make a component named current-user:

<span>
  <slot>{{ user.lastName }}</slot>
</span>
Copy the code

The parent component references the component of current-user, but wants to replace the last name with the first name:

<current-user>
  {{ user.firstName }}
</current-user>
Copy the code

This approach does not work because the user object is the child component’s data and cannot be retrieved from the parent component. In this case, we can implement v-slot.

First bind user as a feature of the

element in the child component:

<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>
Copy the code

We can then define the name of the slot prop we provide with a value for v-slot when referenced by the parent component:

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>
Copy the code

This method also has the abbreviation syntax, you can view the exclusive default slot abbreviation syntax, finally we refer to the following:

<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
</current-user>
Copy the code

The slot-scope code is cleaner and easier to understand than before.

5 Attribute event transmission

When writing high-order components, you may encounter the situation of passing down processed attributes. If you encounter a large number of attributes, you need to pass them one by one, which is very unfriendly and time-consuming. This. Props})? The answer is v-bind and V-ON.

For example, if we have a basic component called BaseList, which has only a basic list function, and we want to add a sorting function to it, we can create a higher-order component called SortList.

<! -- SortList --> <template> <BaseList v-bind="$props" v-on="$listeners"> <! -... --> </BaseList> </template> <script> import BaseList from "./BaseList"; Import BaseListMixin from "./BaseListMixin"; Import sort from "./sort.js"; export default { props: BaseListMixin.props, components: { BaseList } }; </script>Copy the code

You can see the convenience of passing properties and events instead of passing them individually

Functional components

Functional components, that is, stateless, cannot be instantiated, do not have any internal lifecycle processing, are very lightweight and therefore render performance is high, especially suitable for components that change only depending on external data passing.

It is written as follows:

  1. intemplateThe inside of the label saysfunctional
  2. We only acceptpropsvalue
  3. Don’t needscriptThe label
<! -- App.vue --> <template> <div id="app"> <List :items="['Wonderwoman', 'Ironman']" :item-click="item => (clicked = item)" /> <p>Clicked hero: {{ clicked }}</p> </div> </template> <script> import List from "./List"; export default { name: "App", data: () => ({ clicked: "" }), components: { List } }; </script>Copy the code
<! <div> <p v-for="item in props. Items "@click="props. ItemClick (item);" > {{ item }} </p> </div> </template>Copy the code

7 Listen for the life cycle of the component

If the Parent component listens to the mounted component, then the Parent component does some logical processing.

// Parent.vue
<Child @mounted="doSomething"/>

// Child.vue
mounted() {
  this.$emit("mounted");
}
Copy the code

There is a very simple way that the child component does not need to do anything, just need to use @hook to listen when the parent component refers to it. The code is rewritten as follows:

<Child @hook:mounted="doSomething"/>
Copy the code

Mounted, created, updated, and other lifecycle events can be monitored

Reference links:

  • vueTips
  • vuePost

The last

No matter you are a zero-based cute new, or want to change the small partner, as long as you want to understand the front end, proficient in the front end, you are welcome to join our front end self-study group.

Here, you can find like-minded friends, learning partners who encourage each other, and the opportunity to share the experience of the great god and participate in the actual project. If you want to join a self-study group, do it now

From students to bigwigs, there are free resources to share.

In order to help you better review the key knowledge and prepare for the interview more efficiently, the electronic draft of “Front-end Engineer Interview Manual” is specially organized.

Content includes HTML, CSS, JavaScript, ES6, computer networking, browsers, engineering, modularity, Node.js, frameworks, data structures, performance optimization, projects, etc. (The data in this paper are suitable for 0-2 years)

It includes questions asked by first-tier Internet companies such as Tencent, Bytedance, Xiaomi, Ali, Didi, Meituan, 58, Pindoduo, 360, Sina, Sohu and so on, covering the primary and intermediate front-end technology points.

Front end test summary

JavaScript

performance

linux

Front-end data summary

The full PDF is free to share, just like it,Just click here and get it for free.