vue之自定义插件

1、插件的作用

  • 插件通常会为 Vue 添加全局功能,一般是添加全局方法/全局指令/过滤器等
  • Vue 插件有一个公开方法 install ,通过 install 方法给 Vue 添加全局功能
  • 通过全局方法 Vue.use() 使用插件,它需要在你调用 new Vue() 启动应用之前完成.

2、开发插件并且使用

在项目目录下创建plugins.js文件,用于写入插件内容

(function () {

  const MyPlugin = {} //声明一个插件对象

  MyPlugin.install = function (Vue, options) {
    // 1. 添加全局方法或属性
    Vue.myGlobalMethod = function () {
      alert("添加全局方法或属性")
    }

    // 2. 添加全局资源
    Vue.directive('my-directive', {
      inserted: function (el, binding) {
        el.innerHTML = binding.value
      }
    })

    // 3. 注入组件选项
    Vue.mixin({
      created: function () {
        // 逻辑...
      }
    })

    // 4. 添加实例方法,可以传参
    Vue.prototype.$myMethod = function () {
      alert('添加实例方法')
    }

  }
  // 将插件添加到 window 对象中
  window.MyPlugin = MyPlugin

})()

在index.html中进行引入,并且使用:

  • 引入文件
<script src="./plugins.js"></script>
  • 通过全局方法 Vue.use() 使用插件
Vue.use(MyPlugin)
  • 使用
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <button v-my-directive="msg"></button> <!--使用指令-->
</div>

<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./plugins.js"></script>

<script>

  Vue.use(MyPlugin)

  var vm = new Vue(
    {
      el: '#app',
      data: {
        msg: 'hello'
      },
      // 在 `methods` 对象中定义方法
      methods: {
      }
    }
  )
  //调用自定义的全局方法,Vue 调用
  Vue.myGlobalMethod()
  // 调用 Vue 实例方法,vm实例调用
  vm.$myMethod()

</script>

</body>
</html>

3、axios插件化

axios用于发送请求,但是在项目中时常需要引入,可以利用插件,做成全局的插件,这样不需要每一个页面都进行引入

  • 在项目目录下建立对应的插件文件

  • 写对应的实例方法
import axios from 'axios'

const MyHttpServer = {}

MyHttpServer.install = (Vue) => {

  axios.defaults.baseURL = 'http://127.0.0.1:8000/api/'

  //添加实例方法
  Vue.prototype.$http = axios

}

export default MyHttpServer
  • 在main.js中全局导入
import MyHttpServer from '@/plugins/http'

Vue.use(MyHttpServer)
  • 在需要的地方可以进行使用了
 this.$http.post('addUser',data)

猜你喜欢

转载自www.cnblogs.com/shenjianping/p/11315839.html