Vue 插件
功能:增强 Vue
本质:包含 install 方法的一个对象,install 的第一个参数是 Vue,第二个以后的参数是插件使用者传递的数据
定义插件
对象.install = function (Vue, options) {
// 添加全局过滤器
Vue.filter(...)
// 添加全局指令
Vue.directive(...)
// 配置全局混入
Vue.mixin(...)
// 添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = function = xxx
}
使用插件:Vue.use()
实例
src 文件结构
|-- src
|-- App.vue
|-- main.js
|-- plugins.js
|-- components
|-- School.vue
|-- Student.vue
App.vue
<template>
<div id="app">
<School/>
<hr>
<Student/>
</div>
</template>
<script>
import School from "@/components/School";
import Student from "@/components/Student";
export default {
name: 'App',
components: {
School,
Student
},
data() {
return {}
}
}
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
// 引入插件
import plugins from "@/plugins";
Vue.config.productionTip = false
// 应用插件
Vue.use(plugins)
new Vue({
render: h => h(App),
}).$mount('#app')
plugins.js
export default {
install(Vue) {
console.log('@ install', Vue)
// 全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 3)
})
// 定义混入
Vue.mixin({
data() {
return {
a: 1,
b: 2
}
}
})
// 给 Vue 原型上添加一个方法
Vue.prototype.hello = () => {
alert('你好')
}
}
}
School.vue
<template>
<div class="school">
<h2>学校名称:{{name | mySlice}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="test">测试 Hello</button>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
name: 'ABCabc',
address: '长沙',
}
},
methods: {
test(){
this.hello()
}
}
}
</script>
Student.vue
<template>
<div class="school">
<h2>姓名:{{name}}</h2>
<h2>性别:{{sex}}</h2>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男'
}
}
}
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本