[Full version] 7 unpopular but practical tips in Vue.js development

Vue.js is a very popular JavaScript framework that is widely used in front-end development. The following are some unpopular knowledge points in Vue.js:

1. Custom Directives

The instructions in Vue.js can help us manipulate DOM elements. For example, the v-model instruction can bind input boxes and data, and the v-show instruction can display or hide elements based on conditions. But Vue.js also allows us to create custom directives, thus extending its functionality. Custom instructions can be used to handle DOM events, manipulate DOM properties, add styles, and more.

Here is an example where we create a custom instruction v-delay that delays triggering click events:

<template>
  <button v-delay="500" @click="handleClick">Click me</button>
</template>

<script>
  export default {
    directives: {
      delay: {
        inserted: function (el, binding) {
          el.addEventListener('click', function () {
            setTimeout(function () {
              binding.value()
            }, binding.arg)
          })
        }
      }
    },
    methods: {
      handleClick: function () {
        console.log('The click event was triggered delayed')
      }
    }
  }
</script>

In the above code, we define a custom instruction v-delay and bind it to the button. Its parameter is 500, which means a delay of 500ms to trigger the click event. We listen for click events in the inserted hook of the instruction and use the setTimeout function to delay triggering binding.value(), which is the handleClick function.

2. Dynamic Components

Vue.js allows us to use one component to dynamically render another component, which allows us to dynamically switch components as needed.

Here is an example where we create a dynamic component and use the v-bind directive to dynamically bind the component type:

<template>
  <div>
    <button @click="toggleComponent">Toggle component</button>
    <component v-bind:is="currentComponent"></component>
  </div>
</template>

<script>
  import ComponentA from './ComponentA.vue'
  import ComponentB from './ComponentB.vue'

  export default {
    data: function () {
      return {
        currentComponent: 'ComponentA'
      }
    },
    components: {
      ComponentA,
      ComponentB
    },
    methods: {
      toggleComponent: function () {
        this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
      }
    }
  }
</script>

In the above code, we define a dynamic component and use the v-bind directive to dynamically bind the component type, with the initial value being ComponentA. We switch the component type in the toggleComponent method. If it is currently ComponentA, switch to ComponentB, otherwise switch to ComponentA.

3. Slots

Slots in Vue.js are a powerful feature that allow us to insert the content of child components into parent components, thereby creating flexible component structures.

Here is an example where we create a parent component and use slots to insert the content of the child component:

htmlCopy code
<template>
  <div>
    <h2>{<!-- -->{title}}</h2>
    <slot></slot>
  </div>
</template>

<script>
  export default {
    props: ['title']
  }
</script>

In the above code, we create a parent component which has a title and a slot. We use the content of the child component in the slot, and its content will be rendered into the parent component.

Here is an example using a parent component, where we use a child component within the parent component and insert the child component’s content into the parent component’s slot:

htmlCopy code
<template>
  <div>
    <my-component title="This is the title of the parent component">
      <p>This is the content of the child component</p>
    </my-component>
  </div>
</template>

<script>
  import MyComponent from './MyComponent.vue'

  export default {
    components: {
      MyComponent
    }
  }
</script>

In the above code, we are using the MyComponent component in the parent component and passing a paragraph tag as the content of the slot. In the parent component, the paragraph tag will be rendered at the slot position.

4. Mixin

Mixin is a way to reuse code in multiple components. It allows us to abstract some common logic and methods, and then mix them into the components that need to use these logic and methods.

Here is a simple example where we create a Mixin called helloMixin, which contains a hello() method, and then mix it into two different components:

const helloMixin = {
  methods: {
    hello() {
      console.log('Hello, world!')
    }
  }
}


const component1 = {
  mixins: [helloMixin],
  created() {
    this.hello()
  }
}


const component2 = {
  mixins: [helloMixin],
  created() {
    this.hello()
  }
}

In the above code, we define a Mixin named helloMixin, which contains a hello() method. We then mix helloMixin into two different components: component1 and component2. In both components, we can use the hello() method defined in helloMixin by calling the this.hello() method.

Mixins can also include other options, such as data, calculated properties, lifecycle hooks, etc. We can define options in Mixin that can be used in any Vue.js component.

5. Custom Filter

Filter is a special syntax used in templates, which can format, filter, sort, etc. data to meet specific needs.

Vue.js provides some built-in filters, such as currency, uppercase, lowercase, capitalize, etc., but We can also customize our own filters.

Here is an example of a custom filter. We create a filter called reverse that reverses a string:

Vue.filter('reverse', function (value) {
  
  return value.toString().split('').reverse().join('')
})

In the above code, we use the Vue.filter() method to register a global filter named reverse. In the definition of the filter, we use an anonymous function to process the data and return the processed result.

Here is an example of using a reverse custom filter. We apply it to a string and it will return the reversed string:

<template>
  <div>
    {<!-- -->{ message | reverse }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, world!'
    }
  }
}
</script>

In the above code, we use the syntax of message | reverse in the template to apply the custom filter reverse, which will return the reversed messageString.

Custom filters are a very practical feature in Vue.js, which allow us to easily format, filter, sort, etc. data to meet specific needs. Mastering custom filters allows us to develop Vue.js applications more flexibly and efficiently.

6. Server-Side Rendering (SSR)

Another less popular but very important Vue.js feature is Server-Side Rendering (SSR). Server-side rendering allows us to move the rendering process of Vue.js applications from the client to the server, thereby improving the performance, SEO friendliness, accessibility, etc. of the application.

Vue.js provides some built-in tools and plug-ins to support server-side rendering, such as the vue-server-renderer module, Vue SSR Guide document, and vue-cli -plugin-ssrplugin, etc.

Here is an example of server-side rendering, where we use the vue-server-renderer module to render a Vue.js application into an HTML string:

const Vue = require('vue')
const serverRenderer = require('vue-server-renderer').createRenderer()

const app = new Vue({
  template: '<div>{<!-- -->{ message }}</div>',
  data: {
    message: 'Hello, world!'
  }
})

serverRenderer.renderToString(app, (err, html) => {
  if (err) {
    console.error(err)
  } else {
    console.log(html)
  }
})

In the above code, we use the vue-server-renderer module’s createRenderer() method to create a server renderer and use renderToString() Method renders a Vue.js application into an HTML string. After rendering is completed, we can get the rendered HTML string in the callback function.

Server-side rendering requires some additional configuration and considerations, such as handling asynchronous data, route matching, static file serving, etc. If you want to learn more about server-side rendering, please refer to the Vue SSR Guide chapter in the official Vue.js documentation.

Server-side rendering is a very important feature in Vue.js, which allows us to improve application performance, SEO friendliness, accessibility, etc. Mastering server-side rendering allows us to develop Vue.js applications more flexibly and efficiently.

7. Render Function

The rendering function allows us to create the virtual DOM of the Vue.js component programmatically, thereby improving development efficiency, code readability, and maintainability.

The rendering function and template syntax of Vue.js are very similar, and they can both be used to create virtual DOM of Vue.js components. The rendering function uses JavaScript code to describe the structure and behavior of the component, while the template syntax uses HTML-like syntax to describe the structure and behavior of the component.

Below is an example of a rendering function. We use the h() function to create a simple Vue.js component:

Vue.component('my-component', {
  render: function (h) {
    return h('div', {
      attrs: {
        id: 'my-component'
      }
    }, 'Hello, world!')
  }
})

In the above code, we use the Vue.component() method to register a Vue.js component named my-component and use it in renderThe h() function is used in the function to create the virtual DOM of the component. The h() function receives three parameters: tag name, attribute object and child node, and it returns a virtual DOM node.

Here is an example of a Vue.js component using render functions, which is equivalent to the template syntax example above:

<template>
  <div id="my-component">
    Hello, world!
  </div>
</template>

<script>
export default {
  render: function (h) {
    return h('div', {
      attrs: {
        id: 'my-component'
      }
    }, 'Hello, world!')
  }
}
</script>

In the above code, we use the render function in the options of the Vue.js component to create the component’s virtual DOM, which is equivalent to the template syntax example.

The rendering function is a very practical function in Vue.js. It allows us to create the virtual DOM of Vue.js components programmatically, thereby improving development efficiency, code readability and maintainability. Mastering the rendering function allows us to develop Vue.js applications more flexibly and efficiently.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Vue entry-level skills treeHomepageOverview 39375 people are learning the system