preface

We may have been using VUE for a long time in normal development, but for any new features or tricks we haven’t found, this article takes you through some common vUE tricks

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

2. 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: {// Changing the value does not trigger the view response this.data.users[0] = newValue
    // Changing the reference still triggers the view response this.data.users = newArray}};Copy the code

3. Eliminate unnecessary 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.

npm i glob-all purify-css purifycss-webpack --save-dev
 
const PurifyCSS = require('purifycss-webpack')
const glob = require('glob-all')
plugins: [// Remove useless CSS
    new PurifyCSS({
      paths: glob.sync([
        // Make the path file for CSS Tree Shaking
        path.resolve(__dirname, './src/*.html'), // Note that we also need to tree shaking HTML files
        path.resolve(__dirname, './src/*.js')])})]Copy the code

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:

In the template tag, declare that functional only accepts props and does not require script tags

<! -- 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";

exportdefault {
  name: "App".data: () = > ({ clicked: "" }),
  components: { List }
};
</script><! -- list.vue functional components --><template functional>
    <div>
    <p v-for="item in props.items" @click="props.itemClick(item);">
      {{ item }}
    </p></div>
 </template>
Copy the code

5. Monitor the lifecycle 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"/>
<Child @hook:updated="doSomething"/>
Copy the code

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

Or the usual unbinding event:

window.addEventListener('resize'.this.handleResize)
this.$on('hook:destroyed'.() = > {
    window.removeventListener('resize'.this.handleResize)
})
Copy the code

For more information about the use of hooks (useMounted,useComputed) see the vue-hook source code

6. The initial Watch is executed immediately

When a watch variable is created, it will not be initialized. In the following example, you need to call it manually at created time.

created() {
  this.fetchUserList();
},
watch: {
  searchText: 'fetchUserList',}Copy the code

This can be done, but it’s a bit cumbersome. We can add the immediate attribute, which is automatically triggered when created (instead of creating), and the code above can be simplified to:

watch: {
  searchText: {
    handler: 'fetchUserList'.immediate: true}}Copy the code

conclusion

The above is commonly used Vue development skills, I hope to help you