vue mixins组件复用的方式
2019-09-23 08:46:29来源:爱站网 阅读 ()
我们在做功能的时候无意中研究了一下mixins,发现mixins的妙处非常之多,对于不了解的小伙伴们来说就不知道vue mixins组件复用的方式,那么我们现在就一起去了解了解吧。用的时候有这样一个场景,页面的风格不同,但是执行的方法,和需要的数据非常的相似。我们是否要写两种组件呢?还是保留一个并且然后另个一并兼容另一个呢?
不管以上那种方式都不是很合理,因为组件写成2个,不仅麻烦而且维护麻烦;第二种虽然做了兼容但是页面逻辑造成混乱,必然不清晰;有没有好的方法,有那就是用vue的混合插件mixins。混合在Vue是为了提出相似的数据和功能,使代码易懂,简单、清晰。
1.场景
假设我们有几个不同的组件,它们的工作是切换状态布尔、模态和工具提示。这些提示和情态动词不有很多共同点,除了功能:他们看起来不一样,他们不习惯相同,但逻辑是相同的。
//弹框
const Modal = {
template: '#modal',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
},
components: {
appChild: Child
}
}
//提示框
const Tooltip = {
template: '#tooltip',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
},
components: {
appChild: Child
}
}
上面是一个弹框和提示框,如果考虑做2个组件,或者一个兼容另一个都不是合理方式。请看一下代码
const toggle = {
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
const Modal = {
template: '#modal',
mixins: [toggle],
components: {
appChild: Child
}
};
const Tooltip = {
template: '#tooltip',
mixins: [toggle],
components: {
appChild: Child
}
};
用mixins引入toggle功能相似的js文件,进行混合使用
2.可以合并生命周期
//mixin
const hi = {
mounted() {
console.log('this mixin!')
}
}
//vue组件
new Vue({
el: '#app',
mixins: [hi],
mounted() {
console.log('this Vue instance!')
}
});
//Output in console
> this mixin!
> this Vue instance!
先输出的是mixins的数据
3、可以全局混合(类似已filter)
Vue.mixin({
mounted() {
console.log('hello from mixin!')
},
method:{
test:function(){
}
}
})
new Vue({
el: '#app',
mounted() {
console.log('this Vue instance!')
}
})
会在每一个组件中答应周期中的log,同时里面的方法,类似于vue的prototype添加实例方法一样。
var install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (options) {
// 逻辑...
}
}这篇文章主要介绍了vue mixins组件复用的方式,其中vue还提供了一种混合机制mixins,用来更高效的实现组件内容的复用,有兴趣的可以了解一下。
原文链接:https://js.aizhan.com/develop/JavaScript/9041.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:JS注册页面的简单实例
- vue.js开发环境搭建教程 2020-03-16
- Vue input控件通过value绑定动态属性及修饰符的方法 2020-03-05
- 详解Webstorm 新建.vue文件支持高亮vue语法和es6语法 2020-02-07
- vue路由跳转时判断用户是否登录功能的实现 2020-01-17
- vue-cli中打包图片路径错误的解决方法 2020-01-17
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
