百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

今天,学会这5个Vue高级实战技巧就够了

bigegpt 2024-08-29 11:26 4 浏览

作者:maomin9761 来源: 前端历劫之路

前言

今天,我们来分享几个不可不知的vue高级实战技巧。

技巧

自动注册组件

我们平时可能这样引入注册组件。每次都得需要在头部引入,然后注册,最后在模板上使用。

<template>   <div id="app">     <HelloWorld msg="Welcome to Your Vue.js App"/>   </div> </template>  <script> import HelloWorld from './components/HelloWorld.vue'  export default {   name: 'App',   components: {     HelloWorld   } } </script> 

那么,有没有更加方便快捷的方法呢?我们不妨这样。

创建一个名为globalRC.js文件,假设我们这里与组件平级,即存放在组件文件夹中。

目录结构如:

-src --components ---component1.vue ---globalRC.js 

globalRC.js:

import Vue from 'vue'  function changeStr (str){     return str.charAt(0).toUpperCase() + str.slice(1); }  const requireComponent = require.context('./',false,/\.vue$/); // './'操作对象为当前目录  requireComponent.keys().forEach(element => {     const config = requireComponent(element);      const componentName = changeStr(         element.replace(/^\.\//,'').replace(/\.\w+$/,'')     )          Vue.component(componentName, config.default || config) }); 

然后,我们需要在main.js文件中引入。

import './components/globalRC.js' 

最后,我们只需要在模板直接使用就可以了。

<template>   <div id="app">     <Component1 />   </div> </template>  <script> export default {   name: 'App' } </script> 

注意,require.context是webpack的一个API,所以,需要基于webpack环境才可以使用。

自动注册路由

这是我们之前注册路由的方式。如果路由文件多了,会显得特别臃肿。

import Vue from "vue"; import VueRouter from "vue-router"; // 引入组件 import home from "../views/home.vue"; import about from "../views/about.vue";   // 要告诉 vue 使用 vueRouter Vue.use(VueRouter);   const routes = [     {         path:"/",         component: home     },     {         path: "/about",         component: about     } ]   var router =  new VueRouter({     routes })  export default router; 

我们可以这样优化一下。

在路由文件夹下,这里假设是名为router文件夹下,创建一个routeModule.js文件。

目录结构如:

-src --router ---index.js ---login.module.js ---routeModule.js 

routeModule.js:

const routerList = [];  function importAll(r){     r.keys().forEach(element => {         routerList.push(r(element).default);     }); }  importAll(require.context('./',true,/\.module\.js/));// 这里自定义为.module.js 结尾的文件 export default routerList 

然后,我们只需要创建对应的路由文件,如:login.module.js。

export default {     path:'/login',     name:'login',     component:()=>import('../views/login.vue') } 

最后,在路由配置文件index.js中引入routeModule.js文件即可,

import Vue from "vue"; import VueRouter from "vue-router"; import routerList from './routeModule.js'   Vue.use(VueRouter);    var router =  new VueRouter({     routerList })  export default router; 

注意,require.context是webpack的一个API,所以,需要基于webpack环境才可以使用。

权限自定义指令

平常,我们可能会遇到按钮级别或者页面内操作权限的需求,我们可以写一个全局自定义指令。首先,可以在入口文件main.js文件中。

import Vue from 'vue' import App from './App.vue'  function checkArray(key){     let arr = [1,2,3,4]; // 自定义权限列表     let index = arr.indexOf(key);     if(index>-1){         return true     }else{         return false     } }  Vue.directive('auth-key',{   inserted(el,binding){     let displayKey = binding.value;     if(displayKey){       let hasPermission = checkArray(displayKey);       if(!hasPermission){         el.parentNode && el.parentNode.removeChild(el);       }       else{         throw new Error('需要key')       }     }   } })  new Vue({   render: h => h(App), }).$mount('#app') 

在页面中使用。

<button v-auth-key="8">btn</button>  

render渲染函数

我们首先来看下这样一个例子,你会看到模板上特别多的条件判断。

<template>     <div>         <h1 v-if="level === 1"></h1>         <h2 v-else-if="level === 2"></h2>         <h3 v-else-if="level === 3"></h3>         <h4 v-else-if="level === 4"></h4>     </div> </template> 

怎么才能优化呢?接下来,我们可以使用render渲染函数。

Vue.component('anchored-heading', {   render: function (createElement) {     return createElement(       'h' + this.level,   // 标签名称       this.$slots.default // 子节点数组     )   },   props: {     level: {       type: Number,       required: true     }   } }) 

局部引入第三方UI框架优化

我们经常使用UI框架,如果我们使用按需加载的话,需要每次都要注册使用一下。就像下面这样:

import Vue from 'vue'; import { Button, Select } from 'element-ui'; import App from './App.vue';  Vue.component(Button.name, Button); Vue.component(Select.name, Select); /* 或写为  * Vue.use(Button)  * Vue.use(Select)  */  new Vue({   el: '#app',   render: h => h(App) }); 

我们可以这样优化一下,创建一个uIcompontents.js文件。

// 每次只需要在这添加组件即可 import { Button, Select } from 'element-ui';  const components = { Button, Select };  function install(Vue){     Object.keys(components).forEach(key => Vue.use(components[key])) }  export default { install } 

然后,在main.js文件中引入。

import Vue from 'vue' import App from './App.vue';  import uIcompontents from "./uIcompontents.js"; Vue.use(uIcompontents);  new Vue({   el: '#app',   render: h => h(App) }); 

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...