准备
首先在src下建立一个plugins.js文件
然后再文件中建立一个对象,对象里包含install
在main.js中引入并应用插件
在页面控制台如果看到这个,证明应用成功
功能:用于增强Vue
本质:
一:包含install方法的一个对象,install的第一个参数是Vue
引入一个Vue参数
在控制台我们可以看到,这个Vue行参,就是vue的构造函数
二:第二个以后的参数是插件使用者传递的数据
定义插件:
对象.install=function (Vue,options){
//1.添加全局过滤器
Vue.filter(....)
//2.添加全局指令
Vue.directive(....)
//3.添加全局混入(合)
Vue.mixin(....)
//4.添加实例方法
Vue.prototype.$myMethod = function () => {....}
Vue.prototype.$myPrototy = xxxx
}
在plugins.js中加上我们之前学过的过滤器、指令、混入、vc和vm原型,代码如下:
export default {
install(Vue) {
// 全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 4)
})
//定义全局指令
Vue.directive('fbind', {
//指令与元素成功绑定时(一上来)
bind(element, binding) {
console.log('bind')
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element) {
console.log('inserted')
element.focus()
},
//指令所在的模板被重新解析时
update(element, binding) {
console.log('update')
element.value = binding.value
element.focus()
},
})
//定义mixin混入
Vue.mixin({
data() {
return {
x: 1,
y: 2
}
},
})
// 给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello=()=>{
alert('hello呀')
}
}
}
应用插件:Vue.use()
然后我们可以先测试一下过滤器filter能不能实现
页面显示过滤器filter这个方法是被应用了
为了测试指令directive能不能实现
下面页面一刷新input自动获取焦点,也可以证明该方法被使用了
而混入mixin我们可以在这里可以看到它也是被使用了的
最后测试一下Vue原型的hello方法
点击按钮
弹出了'hello呀'字眼,说明hello方法也被成功使用了
总结
本小结主要的代码如下:
MySchool.vue
<template>
<div class="demo">
<h1>学校名:{{ name | mySlice }}</h1>
<h1>学校地址:{{ address }}</h1>
<button @click="test">点我测试一下hello方法</button>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
export default {
name: "MySchool",
data() {
return {
name: "南大pppggg",
address: "南京",
};
},
methods: {
test() {
this.hello();
},
},
};
</script>
MyStudent.vue
<template>
<div class="demo">
<h1>学校姓名:{{ name }}</h1>
<h1>学生年龄:{{ age }}</h1>
<input type="text" v-fbind:value="name">
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
export default {
name: "MyStudent",
data() {
return {
name: "张三",
age: 18,
};
},
};
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
// 引入插件
import plugins from './plugins'
Vue.config.productionTip = false
//应用(使用)插件
Vue.use(plugins,1,2,3)
new Vue({
render: h => h(App)
}).$mount('#app')
plugins.js
export default {
install(Vue,x,y,z) {
console.log('传定义的参数',x,y,z)
// 全局过滤器
Vue.filter('mySlice', function (value) {
return value.slice(0, 4)
})
//定义全局指令
Vue.directive('fbind', {
//指令与元素成功绑定时(一上来)
bind(element, binding) {
console.log('bind')
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element) {
console.log('inserted')
element.focus()
},
//指令所在的模板被重新解析时
update(element, binding) {
console.log('update')
element.value = binding.value
element.focus()
},
})
//定义mixin混入
Vue.mixin({
data() {
return {
x: 1,
y: 2
}
},
})
// 给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello=()=>{
alert('hello呀')
}
}
}