DEV Community

loading...

Write flexible vue logic components in my team

ihavecoke profile image mixbo ・2 min read

Generally if we write logic component which same as computed but different with ui, my team just do this

Vue.js slot

slot can render whatever you want, so if you have multiple logic components but different ui styles, the direct way is create multiple SFC which mean's single file component.

If these SFC have many same logic code, like methods, computed etc, we shouldn't write multiple SFC anymore. we can write parent component and then slot what you want ui child.

// parent.vue
<template>
<div class='parent'>
  <slot :list="list"/>
</div>
</template>

<script>
export default{
  props:{
    slug: String
  },
  methods:{ 
    method1(){},
    method2(){}
  },
  computed:{
    list(){
      return [...]
    }
  }
}
</script>

// AComponent.vue
<template>
 <Parent>
  <template slot-scope='{ list }'>
    <ul class='list'>
     <li v-for='item in list' >{{item}}</li>
    <ul>
  <template>
 </Parent>
</template>

<script>
// ....
</script>

<style scoped type='scss'>
.list{
  background: blue; // here background is blue
}
</style>

// BComponent.vue
<template>
 <Parent>
  <template slot-scope='{ list }'>
    <div class='list>
     <a v-for='item in list'>{{item}}</a>
    </div>
  <template>
 </Parent>
</template>

<script>
// ....
</script>

<style scoped type='scss'>
.list{
  background: red; // here background is red 
}
</style>

You can see we have two components and AComponent list dom is ul
and Bcomponent list dom is 'div'. also AComponent with BComponent has different background color.

Use slot we can easyily isolate logic code and ui style.

Vue.js Mixin

Extract mixin which includes all the commons methods, computed, props .. then component A and B all mixin it.

// _mixin.js
export defeat{
  props:{},
  methods:{ 
    method1(){},
    method2(){}
  },
  computed:{}
}

// A.vue
...
<script>
 import commonMixin from '_mixin.js'
 export default{
   mixin:{commonMixin}
   methods:{
     methoda(){
       this.method1()
     }
   }
 }
</script>
..

// B.vue
...
<script>
 import commonMixin from '_mixin.js'
 export default{
   mixin:{commonMixin}
   methods:{
     methodb(){
       this.method2()
     }
   }
 }
</script>
..

So we can reuse commonMixin methods and just write difference style ui isolated.

Vue.js slot

Discussion (0)

Forem Open with the Forem app