Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the practical tips in the Vue project

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what are the practical tips in the Vue project. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Requirement 1: configure aliases for paths

In the development process, we often need to introduce a variety of files, such as pictures, CSS, JS, etc., in order to avoid writing a long relative path (.. /), we can configure an alias for different directories.

Find the resolve configuration item in webpack.base.config.js and add an alias to its alias, as follows:

Create a CSS file and write any style you want:

.avatar display: flex; justify-content: center; align-items: center;.avatar-img padding 20px border solid 1px # ccc border-radius 5px

Then, you can use it directly in the files we need to introduce:

Export default {name: "Home"} @ import "~ css/avatar"

It should be noted that if it is not introduced through import, you need to precede the alias with ~. The effect is as follows:

Requirement 2: requires that the api address be modified directly in the production package

This demand, how to put it? anyway, it is a demand, so let's find a way to realize it.

Suppose you have an apiConfig.js file to do some configuration for axios, as follows:

Import axios from 'axios';axios.defaults.timeout = 10000 config axios.defaults.retryDelay = 2000briaxios.defaults.responseType =' json';axios.defaults.withCredentials = true;axios.defaults.headers.post ["Content-type"] = "application/json"; / / Add a request interceptoraxios.interceptors.request.use (function (config) {/ / Do something before request is sent return config;}, function (error) {/ / Do something with request error return Promise.reject (error);}) / / Add a response interceptoraxios.interceptors.response.use (function (response) {/ / Do something with response data return response;}, function (error) {/ / Do something with response error return Promise.reject (error);}); export default axios

Add a config.json file to the static folder to manage all api addresses uniformly:

{"base": "/ api", "static": "/ / static.com/api", "news": "/ / news.com.api"}

Open main.js and write the following code:

/ / The Vue build version to load with the `import`command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from'. / App'import router from'. / router'import ElementUI from 'element-ui';import' element-ui/lib/theme-chalk/index.css';import axios from 'js/apiConfig'; / / import is introduced directly without adding ~ Vue.config.productionTip = false;Vue.use (ElementUI) / * eslint-disable no-new * / let startApp = function () {let randomStamp = new Date () .getTime (); axios.get (`/ static/config.json?t=$ {randomStamp}`) .then ((data) = > {axios.defaults.baseURL = data.base; / / set a default root path Vue.prototype.$axios = axios; Vue.prototype.$apiURL = data / / Mount all path configurations to the Vue prototype / * eslint-disable no-new * / new Vue ({el:'# app', router, components: {App}, template:'});}; startApp ()

Is to use axios to get the api file, and then initialize it.

Requirement 3: the backend returns the menu according to the user permission value

The menu is a tree structure (PS: even if it is not a tree structure, you have to deal with it as a tree structure). I use ElementUI here, referring to this article by Dayou, and the implementation is as follows:

Create a new Menu.vue file and write the following code:

Export default {name: "MenuItem", props: {data: {type: Array}, collapse: {type: Boolean}}, methods: {/ / generate menu item createMenuItem (data, createElement) {return data.map (item = > {if (item.children & & item.children.length) {return createElement ('el-submenu', {props: {index: item.id.toString ()}}, [createElement (' template', {slot: 'title'}) [createElement ('class: item.icon}), createElement (' span', [item.title]),]), this.createMenuItem (item.children, createElement) / / Recursive])} else {return createElement ('el-menu-item', {props: {index: item.path}}, [createElement (' class: item.icon}), createElement ('span', {slot:' title'}) [item.title]),])}}, / / Select the menu onSelect (key, keyPath) {console.log (key, keyPath) }, render (createElement) {return createElement ('el-menu', {props: {backgroundColor: "# 545c64", textColor: "# fff", activeTextColor: "# ffd04b", collapse: this.collapse, router:true}, class:'el-menu-vertical-demo', on: {select: this.onSelect}}, this.createMenuItem (this.data) CreateElement))} .el-menu-vertical-demo:not (.el-menu--collapse) {width: 200px Min-height: 400px;}

Two things are mainly used here, one is the render function and the other is recursion. If you are not familiar with the render function, please click here. Some Taoist friends may ask why you don't use templates, because you can't do that. There is only one root element in template, while Vue restricts the use of vMelfort on root elements. Furthermore, by looking at the code in the browser, you can know that the menu is ul plus li. If you have a root element, it will destroy the tag structure (although it does not affect the function, but still feel uncomfortable?). Then, where you need it:

MenuName MeFelixWang import Menu from'@ / components/Menu' Export default {name: 'App', data () {return {menu: [{title:' navigation one', id: 1, path:', icon: 'el-icon-search', children: [{title:' navigation bar one', id: 2, path:', icon:'', children: [{title: 'navigation bar by bar', id: 4, path:'/ test', icon:'' Children: []}, {title: 'navigation one bar, one bar two', id: 5, path:', icon:', children: [{title: 'navigation one bar one bar two bars', id: 6, path:'/ 6 bars, icon:', children: []}, {title: 'navigation one bar one bar two bars', id: 7, path:'/ 7 bars, icon:', children: []} ]},]}, {title: 'navigation one bar and two', id: 3, path:'/ 3 navigation, icon:', children: []}}, {title: 'navigation two', id: 8, path:'/ 8 navigation, icon: 'el-icon-setting', children: []}, {title:' navigation three', id: 9, path:'/ 9navigation, icon: 'el-icon-document' Children: []}, {title: 'navigation four', id: 10, path:', icon: 'el-icon-date', children: [{title:' navigation four bars one', id: 11, path:'/ 11 navigation, icon:', children: []}, {title: 'navigation four bars two', id: 12, path:', icon:', children: [{title: 'navigation four bars and two bars one' Id: 14, path:'/ 14 bars, icon:', children: []}}, {title: 'navigation four bars and three bars', id: 13, path:'/ 13 bars, icon:', children: []},], isCollapsed: false}, methods: {handleOpen (key, keyPath) {console.log (key, keyPath) }, handleClose (key, keyPath) {console.log (key, keyPath);}}, components: {Menu}} * margin 0 padding 0 html, body, .el-container, .el-aside height 100%. El-aside background-color rgb (84,92,100). El-menu border-right solid 1px rgb (84,92,100). El-header display flex justify-content space-between align-items center background-color aliceblue .el-button--text color: # 606266; I font-weight bold

The effect is as follows:

Requirement 4: this Select option is a tree structure, it must be a tree structure

The tree structure is the tree structure, isn't it just the style? it should be fine to change it.

The choices chosen are: {{tree}} export default {name: "Home", data () {return {tree:', options: [], originData: [{label: 'this is the root one', id: 1, children: [{label: 'this is the stem one', id: 2, children: []}, {label: 'this is the stem one or two', id: 3, children: []}, {label: 'this is the stem one three', id: 4 Children: [{label: 'this is Ye one, three, one', id: 6, children: []}, {label: 'this is Ye one, three, two', id: 7, children: []},]}, {label: 'this is stem one and four', id: 5, children: []},]}, {label: 'this is root two', id: 8, children: [],}, {label: 'this is root three'. Id: 9, children: [{label: 'this is Trinity', id: 10, children: []}, {label: 'this is Stem 32', id: 11, children: [{label: 'this is Leaf Trinity', id: 12, children: []},],},]}, created () {this.options = this.decomposeTree (this.originData, 0) }, methods: {/ / decompose the tree structure decomposeTree (array, level) {let tmpArr = []; (function decompose (arr, lev) {for (let I = 0; I < arr.length; iTunes +) {let tmpObj = {}; let item = arr [I]; item.level = lev; tmpObj = Object.assign ({}, item); tmpArr.push (tmpObj); if (item.children) {decompose (item.children, lev + 1) / / Recursive} delete tmpObj.children; / / delete its children to avoid excessive data size (array, level); return tmpArr;} .is-sub:before content'-'

Because option receives an one-dimensional array, the tree structure is flattened recursively, the level of each item is set when flattening, and the indentation and prefix symbols are set through the level. The results are as follows:

The reason for doing this is that the management system is simple and effective, and there is no need to introduce a new plug-in or write one yourself because of this component (except for later use); you can also use input plus tree controls to simulate.

This is the end of this article on "what are the practical tips in the Vue project?" I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report