前端开发那些事儿

vue开发常用技巧总结(一)

2020-09-04  本文已影响0人  小话001

自行整理而成(部分来源于网络)。

1.require与import路由懒加载
const Foo = resolve =>{
 require.ensure(['./Foo.vue',() => {
   resolve(require('./Foo.vue'))
 }])
}
/*******/等价于
const Foo = resolve => require(['./Foo.vue'], resolve);
//在路由中的使用
           第一种:webpack> 2.4 时
           function loadView(view) {
              return () => import(`../pages${view}.vue`);
           }
           {
              path: '/refresh',
              name: 'refresh',
              component: loadView('/home/taskList/refresh')
            },
       //根据路径实际情况
         {
          path:'/',
          name:'home',
          components:resolve=>require(['@/components/home'],resolve)
       }
      第二种:require ,webpack< 2.4 时
      {
       path:'/',
      name:'home',
      components:resolve=>require(['@/components/home'],resolve)
    }  

区别:require:运行时调用,可运行在代码的任何地方。import:编译时调用,必须放在文件开头。

2.require.context()

场景:如果页面需要引用多个组件,原始写法

import titleCom from '@/components/home/titleCom'
import bannerCom from '@/components/home/bannerCom'
import cellCom from '@/components/home/cellCom'
components:{titleCom,bannerCom,cellCom}

便捷的写法:

const path = require('path')
const files = require.context('@/components/home', false, /\.vue$/)
const modules = {}
files.keys().forEach(key => {
  const name = path.basename(key, '.vue')
  modules[name] = files(key).default || files(key)
})
components:modules
3.组件通讯

3.1:props(父传子)

// 数组:不建议使用
props:[]
// 对象
props:{
 inpVal:{
  type:Number, //传入值限定类型
  // type 值可为String,Number,Boolean,Array,Object,Date,Function,Symbol
  // type 还可以是一个自定义的构造函数,并且通过 instanceof 来进行检查确认
  required: true, //是否必传
  default:200,  //默认值,对象或数组默认值必须从一个工厂函数获取如 default:()=>[]
  validator:(value) {
    // 这个值必须匹配下列字符串中的一个
    return ['success', 'warning', 'danger'].indexOf(value) !== -1
  }
 }
}

3.2:$emit(子传父)

// 父组件
<home @title="title">
// 子组件
this.$emit('title',[{title:'这是title'}])

3.3:provide和inject(隔代传参)

//父组件:
provide: { //provide 是一个对象,提供一个属性或方法
  foo: '这是 foo',
  fooMethod:()=>{
    console.log('父组件 fooMethod 被调用')
  }
},
// 子或者孙子组件
inject: ['foo','fooMethod'], //数组或者对象,注入到子组件
mounted() {
  this.fooMethod()
  console.log(this.foo)
}
//在父组件下面所有的子组件都可以利用inject

3.4:公共eventBus(适用于极小的项目)
1.就是声明一个全局Vue实例变量 EventBus , 把所有的通信数据,事件监听都存储到这个变量上;
2.原理就是利用和emit 并实例化一个全局 vue 实现数据共享;

// 在 main.js
Vue.prototype.$eventBus=new Vue()
// 传值组件
this.$eventBus.$emit('eventTarget','这是eventTarget传过来的值')
// 接收组件
this.$eventBus.$on("eventTarget",v=>{
  console.log('eventTarget',v);//这是eventTarget传过来的值
})
4: attrs与$listeners

4.1,attrs使用场景:①如果父传子有很多值那么在子组件需要定义多个解决attrs获取子传父中未在 props 定义的值

// 父组件
<home title="这是标题" width="80" height="80" imgUrl="imgUrl"/>
// 子组件
mounted() {
  console.log(this.$attrs) //{title: "这是标题", width: "80", height: "80", imgUrl: "imgUrl"}
}

②如果子组件定义了 props,打印的值就是剔除定义的属性

props: {
  width: {
    type: String,
    default: ''
  }
},
mounted() {
  console.log(this.$attrs) //{title: "这是标题", height: "80", imgUrl: "imgUrl"}
}

4.2:子组件需要调用父组件的方法解决父组件的方法可以通过listeners" 传入内部组件——在创建更高层次的组件时非常有用,如果是孙组件要访问父组件的属性和调用方法,直接一级一级传下去就可以

// 第一种父组件
<home @change="change"/>

// 子组件
mounted() {
  console.log(this.$listeners) //即可拿到 change 事件
}
//第二种:子组件中
methods: {
      childMethod() {
        this.$parent.fatherMethod();
      }
}
//第三种:子组件中,然后父组件监听这个事件,父:  <child @fatherMethod="fatherMethod"></child>
methods: {
      childMethod() {
        this.$emit('fatherMethod');
      }
}
//第四种:父组件把方法传入子组件中,在子组件里直接调用这个方法
//父
<div>
    <child :fatherMethod="fatherMethod"></child>
  </div>
//子
    <button @click="childMethod()">点击</button>
 props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
5.parent和children(两个均非响应式)
//父组件
mounted(){
  console.log(this.$children) 
  //可以拿到 一级子组件的属性和方法
  //所以就可以直接改变 data,或者调用 methods 方法
}

//子组件
mounted(){
  console.log(this.$parent) //可以拿到 parent 的属性和方法
}
上一篇 下一篇

猜你喜欢

热点阅读