最近在做项目的时候,研究了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组件

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“vue mixins组件复用的几种方式(小结)”

暂无“vue mixins组件复用的几种方式(小结)”评论...

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?