基本概念:
- 插件通常用来为 Vue 添加全局功能 。一般在使用插件时都使用
Vue.use(xxx)
封装插件:
-
创建插件:
// 定义一个插件对象 var pluginObj = {} // 给插件对象添加一个 `install` 方法 pluginObj.install = function (Vue) { // 可以给 Vue 添加一些全局的方法了 } // 将插件对象暴露出去 export default pluginObj
-
使用插件:
// 调用 `MyPlugin.install(Vue)` Vue.use(MyPlugin) new Vue({ // ...组件选项 })
注意点:
- 使用插件:
- 插件的使用代码必须放到创建
vue
实例之前 - 使用
use
方法来使用插件 use
方法其实相当于是调用插件的install
方法
- 插件的使用代码必须放到创建
- 创建插件:
- 插件必须有一个方法 install 方法
- 这个 install 方法有一个参数: vue 构造器
实际操作
import Vue from 'vue'
import router from '@/router/index.js'
import store from '@/store/index.js'
import { Toast } from 'vant'
Vue.use(router)
Vue.use(Toast)
const pluginObj = {}
pluginObj.install = function (Vue) {
Vue.prototype.$login = function () {
const token = store.state.userInfo.token
// 判断
if (!token) {
// 提示用户未登录
Toast('未登录')
// 跳转到登录页面
router.push('/checklogin')
// 返回状态
return false
}
return true
}
}
export default pluginObj
// 在全局main.js里导入插件
import plugin from './utils/myplugin'
// 使用 插件
Vue.use(plugin)
// 点击留言按钮时触发的事件
commit () {
// // 进行登录判断: 如果登录,就继续向下执行;
//如果未登录,就提示用户未登录,跳转到登录页面
// // 得到 token
if (!this.$login()) {
return // 结束后续代码的执行
}
console.log('留言')
}
//登录页面登录的时候做判断,
if (this.$route.path === '/login') {
// 跳转到首页
this.$router.push('/home')
} else {
// 回退到上一个页面
this.$router.back()
}