Vue 2.x – mixin混入/插件
mixin(混入)
-
功能:可以把多个组件共用的配置提取成一个混入对象
-
使用方式:
第一步定义混合:
{ data(){....}, methods:{....} .... }
第二步使用混入:
全局混入:
Vue.mixin(xxx)
局部混入:mixins:['xxx']
<template>
<div>
<h2 @click="showName">学校名:{{ name }}</h2>
<h2>地址:{{ address }}</h2>
</div>
</template>
<script>
import { mixin } from "../mixin"; // 引入mixin.js
export default {
name: "School",
data() {
return {
name: "云淡风轻",
address: "北极",
};
},
mixins: [mixin], // 使用mixin.js中的功能
};
</script>
插件
-
功能:用于增强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 = xxxx }
-
使用插件:
Vue.use()
// main.js // 引入vue import Vue from 'vue' // 引入App import App from './App.vue' // 引入插件 import plugins from './plugins' // 关闭生产提示 Vue.config.productionTip = false // 应用插件 Vue.use(plugins) // 创建Vm new Vue({ el: '#app', render: h => h(App) })
// plugins.js export default { install(Vue) { console.log("@@@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() }, // 指令所在元素被重新解析时 update(element, binding) { element.value = binding.value } }) // 定义混入 Vue.mixin({ data() { return { x: 100, y: 300 } }, }) // 给Vue原型添加一个方法(vm和vc就都能用了) Vue.prototype.hello = () => { alert('hello') } } }
版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/121.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
海报
Vue 2.x – mixin混入/插件
mixin(混入)
功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
第一步定义混合:
{
data(){....},
methods:{....}
....
}
第二……

共有 0 条评论