事关Vue开发的一些小技巧

137 阅读1分钟

「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

写在前面:这是一些在Vue开发过程中,能经常使用到的代码语法,作用一般是既能提升代码性能又能显得代码优雅简洁,而且原理也不复杂,并没有多高级高深,只不过是换了一个角度解决问题.哪怕学到一个没用过的也赚了不是.

事关Vue开发的一些小技巧

路由匹配值

//一般写法
:class="{ 
  'classOnlyOnThesePages' : 
  $route.name === 'Home'
  || $route.name === 'Gallery' 
  || $route.name === 'Profile'
}"
//简便写法
:class="{ 
  'classOnlyOnThesePages' : 
  ['Home', 'Gallery', 'Profile'].includes($route.name)
}"

全局应用某方法

//Vue2
import Utils from './utils/utils.js'

Vue.prototype.$utils = Utils

//Vue3
import Utils from './utils/utils.js'   // <-- import file
const app = createApp(App)

app.config.globalProperties.$utils = Utils   // <-- set globally
app.mount('#app')

异步组件

<!--simple-->
components:{
    Button: () => import ('@/components/Button/Button.vue')
}
<!--complex-->
    const AsyncComponent = () => ({
      // 需要加载的组件 (应该是一个 `Promise` 对象)
      component: import('./MyComponent.vue'),
      // 异步组件加载时使用的组件
      loading: LoadingComponent,
      // 加载失败时使用的组件
      error: ErrorComponent,
      // 展示加载时组件的延时时间。默认值是 200 (毫秒)
      delay: 200,
      // 如果提供了超时时间且组件加载也超时了,
      // 则使用加载失败时使用的组件。默认值是:`Infinity`
      timeout: 3000
    })

第三方组件封装

  • $attr和inheritAttrs
//MyInput.vue
<template>
  <div>
    <el-input v-model="input" v-bind="$attrs" v-on="$listeners"></el-input>
  </div>
</template>

//组件之间传入第三方组件的属性
<MyInput :size="large" :type="primary" :num="90" :disable="true" ></MyInput>
  • $listeners
//MyInput.vue
<template>
  <div>
    <el-input v-model="input" v-bind="$attrs" v-on="$listeners"></el-input>
  </div>
</template>

//组件调用直接使用第三方组件的方法
<MyInput @click="TagClick" @change="Toggle"></MyInput>

限制props的值

export default {
  name: 'Image',
  props: {
    src: {
      type: String,
    },
    style: {
      type: String,
      validator: s => ['square', 'rounded'].includes(s)
      <!--可以限制style的值只能是数组中的值-->
      validator: return lintLength.length < 6
      <!--也可以限制style的值的长度-->
    }
  }
};

避免插槽出现空的div

<template>
  <div>
    <h2>A wrapped slot</h2>
    <div v-if="$slots.default" class="styles">
      <slot />
    </div>
  </div>
</template>

v-for中的解构

//直接取属性
<li
  v-for="{ name, id } in users"
  :key="id"
>
  {{ name }}
</li>

//取索引
<li v-for="(movie, index) in [  'Lion King',  'Frozen',  'The Princess Bride']">
  {{ index + 1 }} - {{ movie }}
</li>

End