vue advanced use vue Use () encapsulates its own plug-in

Posted by rowanparker on Thu, 27 Jan 2022 20:49:48 +0100

prelude

Learning a new knowledge should have some purpose, or understand the relevant background, and learn something with questions, at least not so painful. (don't tell me that learning is happy. Where does learning bring happiness ( ̄  ̄  ̄) ( ̄  ̄  ̄)

Let's first look at a scenario, a very common and simple requirement, which dynamically displays the current system time.

For example, if we want to display the time on the login page now, we can do so

talk is cheap,show you my code

<template>
  <div class="">
    {{ currentDate | transfromDate }}
  </div>
</template>

<script>
// moment.js is a JavaScript date processing class library
import moment from 'moment'
export default {
  name: 'Login',
  data () {
    return {
      currentDate: new Date(),
      // Timer instance
      timer: null
    }
  },
  props: {},
  components: {},
  computed: {},
  watch: {},
  created () {
    // The time is incremented every second
    this.timer = setInterval(() => {
      this.currentTime = new Date()
    }, 1000)
  },
  mounted () {},
  filters: {
    transfromDate: value => {
      const momentInstance = moment(value)
      // This is the current time to return directly to the system
      return momentInstance.format('YYYY[year]MM[month]DD[day] HH:mm:ss')
    }
  },
  methods: {},
  beforeDestoryed () {
    // Clear timer instance before component destruction
    clearInterval(timer)
    this.timer = null
  }
}
</script>

<style scoped lang="less"></style>

This is indeed a problem, but the question comes. Is there a more advanced way to write it, that is, can we find a way to separate some code from the Login component and encapsulate the filtered part of the code? The answer is yes.

theme

Let's introduce our protagonist.

Vue's install method allows us to freely develop our own Vue plug-ins.

Don't say much. Write the code first and then explain it

Create a new filter folder under the src directory of the project, and create a transfromdate under the filter folder JS file, write the following code

import moment from 'moment'
/* Time conversion filter, if you can't understand it, just know it in main Execute Vue. JS file use(transfromDate),
The install function can be executed automatically */
export const transfromDate = {
  install: (Vue) => {
    Vue.filter('transfromDate', (value) => {
      const momentInstance = moment(value)
      return momentInstance.format('YYYY[year]MM[month]DD[day] HH:mm:ss')
    })
  }
}

At this time, someone may ask, paste a code and don't explain it? Don't panic. Keep looking down. (~ ̄▽ ̄)~

Entry file main JS import

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import * as echarts from 'echarts'
// For the function of the css file, please refer to the website https://www.cnblogs.com/ympjsc/p/12309784.html
import 'normalize.css/normalize.css'
// Global css configuration
import 'assets/css/globol.less'
// Hungry UI framework
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// The js file can dynamically adjust the rem reference value according to the change of screen width
import '../public/js/flexible'
// Time conversion filter
import { transfromDate } from './filter/transfromDate'
// The v-title instruction can change the title according to the passed in value
import { vTitle } from './directives/vTitle'
import 'assets/css/iconfont.less'
// Import theme
import '../public/static/theme/dark'
import '../public/static/theme/light'
// The prototype registers echarts so that this is used in the component$ Ecarts will do
Vue.prototype.$echarts = echarts
Vue.use(ElementUI)
Vue.use(vTitle)
Vue.use(transfromDate)

You just need to pay attention to these two sentences

import { transfromDate } from './filter/transfromDate'
Vue.use(transfromDate)

When executing Vue When using (transformdate), Vue will find transformdate JS, and then execute it. What do we do with this install method? Yes, it encapsulates a global time conversion filter.

Vue's install method accepts two parameters. The first is the Vue class and the second is the options configuration item. However, I haven't used the options configuration item in relevant projects yet. I'll supplement it when I use it.

In main JS, our login Vue code can be modified. The transformation is as follows

<template>
  <div class="">
    {{ currentDate | transfromDate }}
  </div>
</template>

<script>
// moment is a JavaScript date processing class library
export default {
  name: 'Login',
  data () {
    return {
      currentDate: new Date(),
      // Timer instance
      timer: null
    }
  },
  props: {},
  components: {},
  computed: {},
  watch: {},
  created () {
    // The time is incremented every second
    this.timer = setInterval(() => {
      this.currentTime = new Date()
    }, 1000)
  },
  beforeDestoryed () {
    // Clear timer instance before component destruction
    clearInterval(timer)
    this.timer = null
  }
}
</script>

<style scoped lang="less"></style>

In fact, the filter part is extracted and encapsulated into a global filter plug-in.

summary

Vue. Use (object name)

The object name should expose an install method when executing Vue When using, the install method of the object will be automatically executed, and then if you want to pass some variables in, you can do this

Vue. Use (object name, {key: value})

Blog

Welcome to my blog www.smartxy.cc

Philosophical moment

The scorching sun in the world was just right, and the wind passed through the forest tops. At that time, we were young.

Topics: Javascript Front-end Vue.js