优雅的使用vue

1 应不应该使用vuex

当全局的变量不超过20,30个时,尽量不要使用vuex,会增加体积。那么有什么方案可以代替vuex呢?

①bus

在main.js全局挂载:Vue.prototype.bus=new Vue();

发送事件:this.bus.$emit('事件名')

接收事件:thia.bus.$on('事件名')

②新建一个store.js

import vue from 'vue';

export const store = vue.observable({a:123});
export const mutations = {
    changea(){
       store.a=456;
    }
}

使用变量a:

computed:{
   a(){
     return a;
   }
}

 

2 针对高频组件的处理

针对需要引用好多次的组件,我们可以在components下边新建一个component,再新建一个index.js集成。

index.js内容

import Vue from 'vue';

function changeStr(str){
   return str.charAt(0).toUpperCase() + str.slice(1);
}

const requireComponent = require.context('./',false,/\.vue$/);
const install = {
   requireComponent.keys.forEach(fileName => {
      let config = requireComponent(fileName);
      let componentName = changeStr(fileName.replace(/^\.\//,'').replace(/\.\w+$/,''))
      Vue.component(componentName,config.default || config);
   })
}

export default { install };

挂载到main.js

import index from 'index.js'
Vue.use(index);

 

3 有的路由有很多子集路由的处理

新建一个route,下面有每个页面的路由,比如index.routes.js,login.routes.js

每个js的内容如下

export default {
   name:'index',
   path:'/index',
   component:''
}

在router下新建一个index.js

const routerList = [];
function importAll(r){
   r.keys().forEach( (key)=>routerList.push(r(key).default))
}
importAll(require.context('../route', true, /\.routes\.js/))

 

4 解决template里边一值多判断

新建一个button.vue

<script>
  export default {
    props:{
       type:{
          type:String,
          default:'normal'
       },
       text:{
          type:String,
          default:'normal'
       }
    },
    render(h) {
       return h('button',{
          class:{
             btn:true,
             'btn-success':this.type === 'seccess',
             'btn-danger':this.type === 'danger' 
          },
          domProps:{
             innerText:this.text || '默认按钮'
          }
       })
    }
  }
</script>

引入并使用

import Button from 'button.vue'

<Button :type = type  :text = text></Button>

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值