mixin混入的主要功能就是将一个众多组件公用的代码片段进行编辑使用,分局部混入和全局混入
看下列示例代码即明白一切
局部混入:
src/mixin.js
:
export const mixin = {
methods: {
showName() {
alert(this.name)
}
},
mounted() {
console.log("你好呀~")
}
}
src/components/School.vue:
学校姓名:{{name}}
学校地址:{{address}}
src/components/Student.vue
:
学生姓名:{{name}}
学生性别:{{sex}}
src/App.vue
:
这样子就实现了将多个组件公用代码片段的混入功能
全局混入:
src/main.js
:
import Vue from 'vue'
import App from './App.vue'
import {mixin} from './mixin'
Vue.config.productionTip = false
Vue.mixin(mixin)
new Vue({
el:"#app",
render: h => h(App)
})
效果图:
2.plugins插件
什么都别说,先来看看示例代码
先定义插件
src/plugin.js
:
export default {
install(Vue,x,y,z){
console.log(x,y,z)
//全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4)
})
//定义混入
Vue.mixin({
data() {
return {
x:100,
y:200
}
},
})
//给Vue原型上添加一个方法(vm和vc就都能用了)
Vue.prototype.hello = ()=>{alert('你好啊')}
}
}
src/main.js
:
import Vue from 'vue'
import App from './App.vue'
import plugin from './plugin'
Vue.config.productionTip = false
//在这里就是要记住使用插件的方法就是Vue.use()
Vue.use(plugin,1,2,3)
new Vue({
el:"#app",
render: h => h(App)
})
src/components/School.vue
:(使用插件当中的过滤方法)
学校姓名:{{name | mySlice}}
学校地址:{{address}}
src/components/Student.vue
:(使用插件当中的原型方法this.hello())
学生姓名:{{name}}
学生性别:{{sex}}
代码示例图解:
plugins插件详解:
插件:
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
定义插件:
plugin.install = function (Vue, options) {
// 1. 添加全局过滤器
Vue.filter(....)
// 2. 添加全局指令
Vue.directive(....)
// 3. 配置全局混入
Vue.mixin(....)
// 4. 添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxxx
}
4.使用插件:Vue.use(plugin)