Home  >  Article  >  Web Front-end  >  Detailed explanation of steps to use Vue Mixin function

Detailed explanation of steps to use Vue Mixin function

php中世界最好的语言
php中世界最好的语言Original
2018-04-28 11:47:162801browse

This time I will give you a detailed explanation of the steps to use the Vue Mixin function. What are the precautions when using the Vue Mixin function. The following is a practical case, let's take a look.

After switching to using Typescript to write Vue applications, after a round of baptism of tool chains and dependencies, I finally started to stumble. However, there is a very commonly used function mixin, and there seems to be no official solution yet.

I want to enjoy the flexibility and convenience of mixins, but also want to reap the security brought by the ts type system and the smooth experience of using IntelliSense during development.

vuejs official organization has a 'vue-class-component' and the recommended 'vue-property-decorator', but there is no corresponding implementation. After looking through the former issue, there is a feature that has been pending for a long time and is mixin support.

It’s not a complicated thing, just write one yourself.

Later note: vue-class-component 6.2.0 starts to provide mixins method, which is similar to the implementation idea of ​​this article.

Implementation

import Vue, { VueConstructor } from 'vue'
export type VClass<T> = {
 new(): T
} & Pick<VueConstructor, keyof VueConstructor>
/**
 * mixins for class style vue component
 */
function Mixins<A>(c: VClass<A>): VClass<A>
function Mixins<A, B>(c: VClass<A>, c1: VClass<B>): VClass<A&B>
function Mixins<A, B, C>(c: VClass<A>, c1: VClass<B>, c2: VClass<C>): VClass<A&B&C>
function Mixins<T>(c: VClass<T>, ...traits: Array<VClass<T>>): VClass<T> {
 return c.extend({
  mixins: traits
 })
}

Declare VClass as a class constructor for T. At the same time, the static methods (extend/mixin and the like) on Vue's constructor are obtained through Pick, so that the real implementation in the following paragraph can be supported. A new subclass is generated by calling the extend method on a Vue subclass constructor. Class constructor.

function Mixins<T>(c: VClass<T>, ...traits: Array<VClass<T>>): VClass<T> {
 return c.extend({
  mixins: traits
 })
}

As for ABC, this is purely a manual job of type declaration.

Usage

In actual use:

import { Component, Vue } from 'vue-property-decorator'
import { Mixins } from '../../util/mixins'
@Component
class PageMixin extends Vue {
 title = 'Test Page'
 redirectTo(path: string) {
  console.log('calling reidrectTo', path)
  this.$router.push({ path })
 }
}
interface IDisposable {
 dispose(...args: any[]): any
}
class DisposableMixin extends Vue {
 _disposables: IDisposable[]
 created() {
  console.log('disposable mixin created');
  this._disposables = []
 }
 beforeDestroy() {
  console.log('about to clear disposables')
  this._disposables.map((d) => {
   d.dispose()
  })
  delete this._disposables
 }
 registerDisposable(d: IDisposable) {
  this._disposables.push(d)
 }
}
@Component({
 template: `
 <p>
  <h1>{{ title }}</h1>
  <p>Counted: {{ counter }}</p>
 </p>
 `
})
export default class TimerPage extends Mixins(PageMixin, DisposableMixin) {
 counter = 0
 mounted() {
  const timer = setInterval(() => {
   if (this.counter++ >= 3) {
    return this.redirectTo('/otherpage')
   }
   console.log('count to', this.counter);
  }, 1000)
  this.registerDisposable({
   dispose() {
    clearInterval(timer)
   }
  })
 }
}
count to 1
count to 2
count to 3
calling reidrectTo /otherpage
about to clear disposables

Notice that the DisposableMixin that directly extends Vue is not a valid Vue component, nor can it be used directly Used in the mixins option, if it is to be used by a self-defined component extended by Vue.extend, remember to use Component to wrap it up.

const ExtendedComponent = Vue.extend({
 name: 'ExtendedComponent',
 mixins: [Component(DisposableMixin)],
})
Abstract class

Mixins used in business systems are actually more complex in most cases, providing some basic functions, but some parts need to be left to the successors to implement themselves. At this time It is appropriate to use

abstract class.

abstract class AbstractMusicPlayer extends Vue {
 abstract audioSrc: string
 playing = false
 togglePlay() {
  this.playing = !this.playing
 }
}
class MusicPlayerA extends AbstractMusicPlayer {
 audioSrc = '/audio-a.mp3'
}
class MusicPlayerB extends AbstractMusicPlayer {
 staticBase = '/statics'
 get audioSrc() {
  return `${this.staticBase}/audio-b.mp3`
 }
}
But abstract classes cannot be instantiated and do not meet the requirement of

{ new(): T }, so they can only be inherited and cannot be mixed in. Due to the same The reason is that abstract classes cannot be decorated by the Component function of 'vue-class-component'.

At this time, we have to write the implemented functions into Mixin, and put the functions to be implemented into the interface and let the specific class implement them.

interface IMusicSourceProvider {
 audioSrc: string
}
/**
 * @implements IPlayerImplementation
 */
class PlayerMixin extends Vue {
 /** @abstract */
 audioSrc: string
 logSrc() {
  console.log(this.audioSrc)
 }
}
interface IPlayerImplementation extends IMusicSourceProvider {}
class RealPlayer extends Mixins(PlayerMixin) implements IPlayerImplementation {
 audioSrc = '/audio-c.mp3'
}
This way of deceiving the compiler is actually quite clumsy. If a specific class inherits PlayerMixin but does not explicitly declare to implement IPlayerImplementation, the compiler cannot tell you this error. We can only carefully write comments in the code and hope that users will not forget this.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Jump back to the homepage after sharing the page

##Detailed explanation of the use of watch method in Vue

The above is the detailed content of Detailed explanation of steps to use Vue Mixin function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn