头图

7 Vue.js patterns you should use frequently

杜尼卜
中文

To be honest, reading documentation is not something that most of us like, but when using a modern front-end framework like Vue that is constantly evolving, many things will change with each new version released, and you may miss some of the later launch The new shiny function. Let's take a look at those interesting but not-so-popular features, remember that all of them are part of the Vue documentation.

1. Handling the loading state

In large applications, we may need to divide the application into smaller pieces and load components from the server only when needed. To make this easier, Vue allows you to define your component as a factory function, which parses your component definition asynchronously. Vue will only trigger the factory function when it needs to render the component, and cache the result for future re-rendering. The new feature of version 2.3 is that the asynchronous component factory can also return an object in the following format.

const AsyncComponent = () => ({
  // 要加载的组件(应为Promise)
  component: import('./MyComponent.vue'),
  // 异步组件正在加载时要使用的组件
  loading: LoadingComponent,
  // 加载失败时使用的组件
  error: ErrorComponent,
  // 显示加载组件之前的延迟。默认值:200ms。
  delay: 200,
  // 如果提供并超过了超时,则会显示error组件。默认值:无穷。
  timeout: 3000
})

In this way, you have additional loading and error status, component acquisition delay and timeout options.

2. Cheap "v-once" static components

Rendering pure HTML elements in Vue is very fast, but sometimes you may have a component that contains a lot of static content. In this case, you can v-once instruction to the root element, and then cache it, just like this.

Vue.component('terms-of-service', {
  template: `
    <div v-once>
      <h1>Terms of Service</h1>
      ... a lot of static content ...
    </div>
  `
})

3. Recursive components

Components can call themselves recursively in their own templates, but they can only be called name

If you are not careful, recursive components can also lead to infinite loops:

name: 'stack-overflow',
template: '<div><stack-overflow></stack-overflow></div>'

Components like the above will cause the "maximum stack size exceeded" error, so make sure that the recursive call is conditional (using v-if will eventually be false )

4. Inline templates

When the special attribute inline-template exists on a subcomponent, the component will use its internal content as its template instead of treating it as distributed content, which allows more flexible template writing.

<my-component inline-template>
  <div>
    <p>These are compiled as the component's own template.</p>
    <p>Not parent's transclusion content.</p>
  </div>
</my-component>

5. Dynamic command parameters

The instruction parameters can be dynamic. For example, in v-mydirective:[argument]=“value" , argument can be updated according to the data attributes in the component instance! This allows our custom instructions to be used flexibly throughout the application.

This is an instruction in which dynamic parameters can be updated based on component instances:

<div id="dynamicexample">
  <h3>Scroll down inside this section ↓</h3>
  <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>
Vue.directive('pin', {
  bind: function (el, binding, vnode) {
    el.style.position = 'fixed'
    var s = (binding.arg == 'left' ? 'left' : 'top')
    el.style[s] = binding.value + 'px'
  }
})

new Vue({
  el: '#dynamicexample',
  data: function () {
    return {
      direction: 'left'
    }
  }
})

6. Events and key modifiers

For .passive , .capture and .once event modifiers, Vue provides prefixes on

E.g:

on: {
  '!click': this.doThisInCapturingMode,
  '~keyup': this.doThisOnce,
  '~!mouseover': this.doThisOnceInCapturingMode
}

For all other events and key modifiers, no proprietary prefix is needed, because you can use event methods in handlers.

7. Dependency Injection (Provide/Inject)

There are several ways to allow two components to communicate in Vue, each of which has advantages and disadvantages. A new method introduced in version 2.2 is to use Provide/Inject dependency injection.

This pair of options are used together to allow an ancestor component to act as a dependency injector for all its descendants, no matter how deep the component hierarchy is, as long as they are on the same parent chain. If you are familiar with React, this is very similar to React's context.

// parent component providing 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// child component injecting 'foo'
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}
阅读 541

前端全栈开发者
专栏首发于公众号《前端全栈开发者》,订阅关注第一时间阅读好文
avatar
杜尼卜
前端工程师

做工程师不做码农、全栈开发工程师、持续学习者

11k 声望
5.6k 粉丝
0 条评论
你知道吗?

avatar
杜尼卜
前端工程师

做工程师不做码农、全栈开发工程师、持续学习者

11k 声望
5.6k 粉丝
宣传栏