vue cli插件plugins的使用

应用场景:vue cli插件plugins中的方法均可以被任意组件调用,增强Vue的功能。

首先在创建好的vue项目的src目录下新建plugins.js:

export default {
  install(Vue) {
    // 全局过滤器
    Vue.filter('mySlice', function(value){
      return value.slice(0, 4);
    });
    
    // 自定义指令
    Vue.directive('fbind', {
      bind(el, binding, vnode) {
        el.value = binding.value;
      },

      inserted(el) {
        el.focus();
      },

      update(el, binding) {
        el.value = binding.value;
      }
    });

    // Vue构造函数原型上添加方法
    Vue.prototype.hello = ()=>{
      console.log('hello');
    }

  }
}

在main.js中引入plugins,并使用Vue.use应用插件:

import Vue from 'vue'
import App from './App'
import plugins from './plugins'

Vue.config.productionTip = false
Vue.use(plugins)

new Vue({
  el: '#app',
  render: h => h(App)
})

School.vue组件中使用插件plugins中的方法:

<template>
  <div>
    <p>学校名称:{
   
   {name | mySlice}}</p>
    <p @click="test">学校地址:{
   
   {address}}</p>
    <input type="text" name="" v-fbind.value="name">
  </div>
</template>

<script>

export default {
  name: 'School',
  data() {
    return {
      message: 'hello world',
      name: 'zz@#1234',
      address: 'bj'
    }
  },
  methods: {
    test() {
      this.hello()
    }
  }
}
</script>

<style>

</style>

页面效果:

猜你喜欢

转载自blog.csdn.net/u010234868/article/details/123153558