plugin插件介绍
1、功能:用于增强Vue
2、本质:Vue中的plugin本质上是一个包含install方法的对象,install方法的第一个参数时Vue构造函数,第二个以后的参数时插件使用者传递的数据(比如:Vue.use(plugins,a,b,c),其中a,b,c就是所传的参数)
3、插件用法
(1)定义插件:
对象.install = function(Vue, options) {
//1、添加全局过滤器
Vue.filter(...)
//2、添加全局指令
Vue.directive(...)
//3、配置全局混入(合)
Vue.mixin(....)
//4、添加实例方法
Vue.prototype.$myMethod = function() {...}
Vue.prototype.$myProperty = xxxx
}
(2)使用插件(在main.js中)
//引入插件
import plugins from '插件路径'
//使用插件
Vue.use()
案例
main.js
/*
该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//引入插件
import plugins from './plugin'
//管比vue产生的提示
Vue.config.productionTip = false
//使用插件
Vue.use(plugins)
//创建vue实例对象 -- vm
new Vue({
el:'#app',
//下面这行代码一会解释,完成了这个功能:将App组件放入容器中
render: h => h(App),
})
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学校姓名:{{name | mySlice}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="test">点我显示一个hello方法</button>
</div>
</template>
<script>
export default {
name:'School',
data(){
return {
name:'尚硅谷bbbbbb',
address:'北京昌平',
}
},
methods:{
test(){
this.hello()
}
}
}
</script>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学生姓名:{{name | mySlice}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>学生年龄:{{age}}</h2>
<input type="text" v-fbind="name"/>
</div>
</template>
<script>
export default {
name:'Student',
data(){
return {
name:'张三aaaaaa',
sex:'男',
age:19,
}
},
}
</script>
plugin.js
export default {
install(Vue){ //这里的Vue是一个Vue的原型方法
//全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4)
})
//定义全局指令
Vue.directive('fbind',{
//指令与元素成功绑定时
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data() {
return {
x:100,
y:200
}
}
})
//给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = ()=>{alert('你好啊!!')}
}
}
效果: