功能:用于增强 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.user()
e3cfbf9174b1f384415721d70316781.png
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) {
element.focus()
},
//指令所在的模板被重新解析时
update(element, binding) {
element.value = binding.value
element.focus()
},
})
// 定义混入
Vue.mixin({
data() {
return {
x: 100,
y:200
}
},
})
// 给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = () => { alert('你好啊') }
}
}
mian.js
import Vue from 'vue'
import App from './App.vue'
// 引入插件
import plugins from './plugins.js'
Vue.config.productionTip = false
// 应用插件
Vue.use(plugins)
new Vue({
render: h => h(App),
}).$mount('#app')
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<input type="text" v-fbind:value="name" />
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
// 第一步:创建学校组件
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男',
}
},
}
</script>
<style scoped>
/* 组件的样式 */
</style>
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>学校名称:{{ name | mySlice }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="test">点我测试一个htllo方法</button>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
// 第一步:创建学校组件
export default {
name: 'School',
data() {
return {
name: '清华大学22222222',
address: '北京',
}
},
methods: {
test() {
this.hello()
},
},
}
</script>
<style scoped>
/* 组件的样式 */
</style>










网友评论