功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
定义插件:
对象.install = function (Vue,options){
//1.全局过滤器
Vue.filter(.....)
//2.添加全局指令
Vue.directive(.....)
//3.配置全局混入(合)
Vue.mixin(.....)
//4.添加实例方法
Vue.prototype.$myMethod = function (){.....}
Vue.prototype.$myProperty = xxx
}
使用插件:Vue.use()
main.js
/*该文件是整个项目的入口文件 */
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//引入插件
import plugins from './plugins'
//关闭vue的生产提示
Vue.config.productionTip = false
Vue.use(plugins)
new Vue({
el: '#app',
//将App组件放入容器中
render: h => h(App),
})
plugins.js
export default{
install(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()
},
ipdate(element, binding) {
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data() {
return {
x: 100,
y:200
}
}
})
//给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = ()=>{alert('你好啊')}
}
}
Student.vue
<template>
<div>
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<input type="text" v-fbind:value="name">
</div>
</template>
<script>
//引入一个hunhe
export default {
name: "Student",
data() {
return {
name: "张三",
sex: "男",
};
}
}
</script>
School.js
<template>
<div>
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<input type="text" v-fbind:value="name">
</div>
</template>
<script>
//引入一个hunhe
export default {
name: "Student",
data() {
return {
name: "张三",
sex: "男",
};
}
}
</script>