• 注册
当前位置:1313e > vue >正文

[vue] Vue中插件的定义 Vue.use()

功能:

用于增强Vue 通常用来为 Vue 添加全局功能
在这里插入图片描述

简单案例

plugins.js

export default {install(){console.log('@install');}
}

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)//创建vm
new Vue({el:'#app',render: h => h(App)
})

在这里插入图片描述

本质:

包含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()

简单案例

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){element.value = binding.value},//指令所在元素被插入页面时inserted(element,binding){element.focus()},//指令所在的模板被重新解析时update(element,binding){element.value = binding.value}})//定义混入Vue.mixin({data() {return {x:100,y:200}},})//给Vue原型上添加一个方法(vm和vc就都能用了)Vue.prototype.hello = ()=>{alert('你好啊')}}
}

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)
//创建vm
new Vue({el:'#app',render: h => h(App)
})

App.js

<template><div><School/><hr><Student/></div>
</template><script>import School from './components/School'import Student from './components/Student'export default {name:'App',components:{School,Student}}
</script>

School.vue

<template><div><!-- 可以使用插件中的mySlice方法 --><h2>学校名称:{{name | mySlice}}</h2><h2>学校地址:{{address}}</h2><button @click="test">点我测试一个hello方法</button></div>
</template><script>export default {name:'School',data() {return {name:'尚硅谷atguigu',address:'北京',}},methods: {test(){// 可以使用插件中给原型添加的方法this.hello()}},}
</script>

Student.vue

<template><div><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>





参考:
Vue中插件的定义

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录