温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue项目中的重复代码怎么利用mixin进行合并

发布时间:2020-11-30 15:58:47 来源:亿速云 阅读:355 作者:Leah 栏目:开发技术

本篇文章为大家展示了Vue项目中的重复代码怎么利用mixin进行合并,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

在vue项目中,我们都知道模块化和组件化,但vue的框架中还有一个很好用的知识点,就是mixin

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

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

     初始页面:

Vue项目中的重复代码怎么利用mixin进行合并

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

Vue项目中的重复代码怎么利用mixin进行合并

      项目的核心结构如下:

Vue项目中的重复代码怎么利用mixin进行合并

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

Child1.vue

<template>
  <div class="Child1">
    <h2>我是子组件1</h2>
    <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">
    <h2>我是子组件2</h2>
    <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">
  <h2>我是父组件</h2>
  <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究竟有啥用呢?那就是代码复用

Vue项目中的重复代码怎么利用mixin进行合并

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

Vue项目中的重复代码怎么利用mixin进行合并

Vue项目中的重复代码怎么利用mixin进行合并

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

上述内容就是Vue项目中的重复代码怎么利用mixin进行合并,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI