Vue项目经验分享:用mixin合并重复代码

此文转载自:https://blog.csdn.net/TB199404/article/details/110089213#commentBox

       在我们做项目的时候,往往有很多代码逻辑是通用的,比如说,业务逻辑类型的判断,时间戳的转换,url中字符串的截取等等,这些函数如果在每个需要的页面中都加入的话,不仅加重了当前页面的逻辑复杂程度,还会占用大量原本可以省略的内存。因此,将这些代码整理出来统一管理是很有必要的,在vue项目中,我们都知道模块化和组件化,但vue的框架中还有一个很好用的知识点,就是mixin

      mixin不仅可以存放data、watch、methods、computed等,还可以存放Vue的生命周期,是不是很神奇呢?

     通过点击按钮“点击我”,实现“难受”和“极好的”相互切换,首先上效果图:

     初始页面:

正在加载中

       子组件1和子组件2都可以通过“点击我”,实现状态改变,通过触发子组件1的按钮1,触发子组件2的按钮2次,效果如下:

正在加载中

      项目的核心结构如下:

正在加载中

       其中,新增了mixin文件夹,新增了Child1.vue和Child2.vue,更改HelloWorld.vue为Father.vue,因为本人有代码洁癖,觉得vueRouter默认的hash模式,会使得前端路由有些难看,所以改成了history模式,项目更改的文件代码如下

Child1.vue

<template>
    <div class="Child1">
        <h1>我是子组件1</h1>
        <p>我现在很{{status}}</p>
        <button @click="submitChange">点击我</button>
    </div>
</template>

<script>
import { Happy } from '../mixin/showHappy'
export default {
    name: "Child1",
    mixins: [Happy]
}
</script>

Child2.vue 

<template>
    <div class="Child2">
        <h1>我是子组件2</h1>
        <p>我现在很{{status}}</p>
        <button @click="submitChange">点击我</button>
    </div>
</template>

<script>
import { Happy } from '../mixin/showHappy'
export default {
    name: "Child2",
    mixins: [Happy]
}
</script>

Father.vue

<template>
  <div class="Father">
    <h1>我是父组件</h1>
    <child1-component />
    <child2-component />
  </div>
</template>

<script>
import Child1Component from './Child1'
import Child2Component from './Child2'
export default {
  name: 'Father',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  components:{
    Child1Component,
    Child2Component
  }
}
</script>

mixin/showHappy.js

/*这里是专门用来进行mixin测试的(通过点击按钮会相应的改变对应状态)*/
export const Happy = {
    data(){
        return{
            isRealHappy:true,
            status: '',
            sad: '难受',
            comfort: '舒服'
        }
    },
    methods:{
        submitChange(){
            if(this.isRealHappy){
                this.isRealHappy = !this.isRealHappy
                this.status = this.comfort
            }else{
                this.isRealHappy = !this.isRealHappy
                this.status = this.sad
            }
        }
    }
}

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Father from '@/components/Father'

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'Father',
    component: Father
  }
]
const routers = new Router({
  mode: 'history',
  routes
})
export default routers

那么,代码贴了这么多,mixin究竟有啥用呢?那就是代码复用

如果我们不用mixin这种方式,直接把这段代码贴到Child1.vue和Child2.vue中,也是可以实现与页面展示一样的效果:

         很显然,mixin的书写方式更优雅,虽然项目中没有这么简单的代码,但这是一种思想!

         让我们更精致一些,让项目让代码尽可能高类聚低耦合,如此一来,我们必然会成为更优秀的程序员!

         顺便提及一下使用小细节,如果在组件中出现了与mixin中相同的属性或方法,会优先展示组件中的属性和方法哦!各位小伙伴,一起加油吧!

     

原文地址:https://www.cnblogs.com/phyger/p/14043662.html