VUE2 project: Shangpinhui VUE-CLI scaffolding initialization project and routing component analysis (1)

environment

The prerequisite is to have node.jsand webpackenvironment, and VUE-CLI needs to be installed. My version is@vue/cli 5.0.8

Vue CLI is a rapid development tool based on Vue.js that can help developers quickly create Vue.js projects. There are the following steps to run a Vue CLI project:

1. Install Vue CLI: Use npm or yarn to install Vue CLI. You can use the following command:

npm install -g @vue/cli

2. Create a Vue project: Use the Vue CLI to create a new Vue project. You can use the following command:

vue create app

Among them, app is the project name.

3. Run the Vue project: Enter the project directory and use the following command to run the Vue project:

cd app
npm run serve

4. Access the Vue application: Access the address of the running Vue project in the browser, which can be seen in the terminal. By default, the application address is: http://localhost:8080/.

If you need to package the project, you can use the following command:

npm run build

This will generate a dist directory containing the packaged application. For specific installation steps, see vue-cli

Loaded directory:
Insert image description here

VUE2 directory

public

Place static resource files. The static file resources in this folder will be packaged intact into the dist folder when webpack packages them.

assets

Place static resources common to each component. When packaging, treat it as a module and package it into a JS file.

components

Place non-routing components, which are global components.

main.js

The program entry file is executed first.

babel.config.js

Babel configuration file. Babel is a JavaScript compiler.

package.json

The dependency information configuration introduced by the project vue-cli-service serve --opencan be started by opening the browser directly.

 "scripts": {
    
    
   "serve": "vue-cli-service serve --open",
   "build": "vue-cli-service build",
   "lint": "vue-cli-service lint"
 }

view.config.js

An optional VUE configuration file that is automatically loaded. It is loaded when the project starts. Use module.exportsthe exposed configuration, such as turning off eslint detection:

module.exports = defineConfig({
    
    
  // 关闭eslint检测
  lintOnSave: false
 })

For details, please refer to: vue-config-js

Project routing analysis

Routing in VUE is vue-routerimplemented, and the core finds the routing component based on the routing address, which is equivalent to key-valuethe operation. This project uses a top, middle and bottom structure. The styles of the top and bottom remain unchanged and change in the middle. The search part in the middle can be separated into a common component.

Top:

Insert image description here

bottom:

Insert image description here
These two parts can be made into a common component unchanged.

Header and bottom components: Header and Footer are used as non-routing components, Home (homepage) and Search (search), and Login are used as routing components.

Header and Footer non-routing components completed

To complete the logic of a VUE project, first draw the page, split the components, dynamically display the data, and process the dynamic data business. When creating a component, you need to find out its structure, style, and static resources.

Header example

Projects that use less to control css styles need to install less and less-loader, execute the command directly: npm install --save less less-loader@5or package.jsondirectly add dependencies to the file, and then npm installdownload:

Insert image description here

Create a new directory Header under componentsthe folder:

Insert image description here
Note that to identify the less style, you need to addlang="less"

<style scoped lang="less">
.footer {
    
    
    background-color: #eaeaea;

    .footer-container {
    
    
        width: 1200px;
        margin: 0 auto;
        padding: 0 15px;

        .footerList {
    
    
            padding: 20px;
            border-bottom: 1px solid #e4e1e1;
            border-top: 1px solid #e4e1e1;
            overflow: hidden;
            padding-left: 40px;

            .footerItem {
    
    
                width: 16.6666667%;
                float: left;

                h4 {
    
    
                    font-size: 14px;
                }

                .footerItemCon {
    
    
                    li {
    
    
                        line-height: 18px;
                    }
                }

                &:last-child img {
    
    
                    width: 121px;
                }
            }
        }

        .copyright {
    
    
            padding: 20px;

            .helpLink {
    
    
                text-align: center;

                li {
    
    
                    display: inline;

                    .space {
    
    
                        border-left: 1px solid #666;
                        width: 1px;
                        height: 13px;
                        background: #666;
                        margin: 8px 10px;
                    }
                }
            }

            p {
    
    
                margin: 10px 0;
                text-align: center;
            }
        }
    }
}
</style>

But I found that the styles were messed up, and I needed to use reset.css to clear the previous default style:

Insert image description here
reset.css

@import "./iconfont.css";
 
/* 清除内外边距 */
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote,
dl, dt, dd, ul, ol, li,
pre,
fieldset, lengend, button, input, textarea,
th, td {
    
    
    margin: 0;
    padding: 0;
}

/* 设置默认字体 */
body,
button, input, select, textarea {
    
     /* for ie */
    /*font: 12px/1 Tahoma, Helvetica, Arial, "宋体", sans-serif;*/
    font: 12px/1.3 "Microsoft YaHei",Tahoma, Helvetica, Arial, "\5b8b\4f53", sans-serif; /* 用 ascii 字符表示,使得在任何编码下都无问题 */
    color: #333;
}


h1 {
    
     font-size: 18px; /* 18px / 12px = 1.5 */ }
h2 {
    
     font-size: 16px; }
h3 {
    
     font-size: 14px; }
h4, h5, h6 {
    
     font-size: 100%; }

address, cite, dfn, em, var, i{
    
     font-style: normal; } /* 将斜体扶正 */
b, strong{
    
     font-weight: normal; } /* 将粗体扶细 */
code, kbd, pre, samp, tt {
    
     font-family: "Courier New", Courier, monospace; } /* 统一等宽字体 */
small {
    
     font-size: 12px; } /* 小于 12px 的中文很难阅读,让 small 正常化 */

/* 重置列表元素 */
ul, ol {
    
     list-style: none; }

/* 重置文本格式元素 */
a {
    
     text-decoration: none; color: #666;}


/* 重置表单元素 */
legend {
    
     color: #000; } /* for ie6 */
fieldset, img {
    
     border: none; }
button, input, select, textarea {
    
    
    font-size: 100%; /* 使得表单元素在 ie 下能继承字体大小 */
}

/* 重置表格元素 */
table {
    
    
    border-collapse: collapse;
    border-spacing: 0;
}

/* 重置 hr */
hr {
    
    
    border: none;
    height: 1px;
}
.clearFix::after{
    
    
	content:"";
	display: block;
	clear:both;
}
/* 让非ie浏览器默认也显示垂直滚动条,防止因滚动条引起的闪烁 */
html {
    
     overflow-y: scroll; }

a:link:hover{
    
    
    color : rgb(79, 76, 212) !important;
    text-decoration: underline;
}

/* 清除浮动 */
.clearfix::after {
    
    
    display: block;
    height: 0;
    content: "";
    clear: both;
    visibility: hidden;
}

Then in the index.html page:<link rel="stylesheet" href="./reset.css">

Insert image description here
Use Header component

To App.vueregister this component use:

Insert image description here

App.vue code:

<template>
  <div>
  	<!--使用组件-->
    <Header></Header>
    <router-view></router-view>
    <Footer v-show="$route.meta.show"></Footer>
  </div>
</template>

<script>
// 导入组件
import Header from './components/Header';
import Footer from './components/Footer';

export default {
    
    
  name: 'App',
  components: {
    
    
    Header,
    Footer
  },
  mounted(){
    
    
    // 只发一次
    this.$store.dispatch('categoryList');
  }
}
</script>
<style>
</style>

The steps to operate the Footer component are the same as those for the Header.

Building routing components

The routing components of the project are divided into four, Home, Search, Login, and Register , and vue-routerrouting needs to be installed npm install --save vue-router. Routing components are generally placed under the pages or views folder.

Insert image description here
Index.js in the router needs to introduce these routing components and expose them to the outside world.

// 导入路由组件
import Vue from 'vue';
import VueRouter from 'vue-router';

// 使用插件
Vue.use(VueRouter);
// 引入路由组件
import Home from '@/pages/Home';
import Search from '@/pages/Search';
import Login from '@/pages/Login';
import Register from '@/pages/Register';

// 配置路由
export default new VueRouter({
    
    
    // 配置路由 
    routes: [
        {
    
    
            path: "/home",
            component: Home,
            meta: {
    
    
                show: true
            }
        },
        {
    
    
            path: "/search/:keyword?",
            component: Search,
            meta: {
    
    
                show: true
            },
            name: 'search'
        },
        {
    
    
            path: "/login",
            component: Login,
            meta: {
    
    
                show: false
            }
        },
        {
    
    
            path: "/register",
            component: Register,
            meta: {
    
    
                show: false
            }
        },
        {
    
    
            // 页面重定向,访问/重定向到首页
            path: "*",
            redirect: "/home"
        },
    ]
});

The above only exposes these components, and these components need to main.jsbe registered in:

Insert image description here
After declaring the router, as long as the component is registered, the component will have $routeattributes, which mainly receive the parameter information carried by the route. For $routerexample, $routerit is used to perform route jumps and carry parameters.

For information about routing, please refer to the vue-router official website .

Finally, if you want the routing to take effect, you need to add it to App.vue:<router-view/>

Insert image description here

Declarative navigation

Use the three links in the picture as an example of declarative navigation. Click the corresponding link to enter the corresponding page, such as clicking on the picture to enter the homepage.
Insert image description here
Specific implementation: use router-linkthe to tag in route jump.

Insert image description here

Programmatic navigation

Programmatic navigation is mainly used for routing that carries parameter jumps. For example, keyword search :

Insert image description here
goSearch()The method defined in the search button

Insert image description here
Implement this method: the internal implementation will be detailed later.

Insert image description here

Showing and hiding the Footer component

If you want to hide the bottom component when logging in or registering, you can use routing meta information to metaconfigure it in the routing configuration file index.js:

Insert image description here
Just use the get value where this Footer component is applied $route.meta.show.

Insert image description here

Route passing parameters

There are two main ways to write routing parameters. The official website explains the difference in detail. The main thing is that paramsit can occupy spaces but cannot occupy spaces.queryparamsquery

Insert image description here
The above briefly talked about programmatic navigation. Next, let’s look at how programmatic navigation transfers parameters.

Take keyword query as an example:

String passing participates in template parameter passing

// 字符串传参
this.$router.push("/search/"+this.keyword+"?k="+this.keyword.toUpperCase())
.catch(err => err)
// 模板传参
this.$router.push(`/search/${
      
      this.keyword}?k=${
      
      this.keyword.toUpperCase()}`)
.catch(err => err)

Object passing parameters

The most common way to pass parameters is through object.

// 对象传参
this.$router.push({
    
    
    name: "search",
    params: {
    
    
        keyword: this.keyword
    },
    query: {
    
    
        k: this.keyword.toUpperCase()
    }
})

Parameters need to be declared in the corresponding route name: "search"to identify this /searchroute and cannot be used directly path.

Use $route.params.keywordwith $route.query.kto get the specified value.

Insert image description here

Rewrite push and replace

Directly use the push or repalce method that comes with Vue. When you click the same route multiple times, the console will report NavigationDuplicatedan error. Although it does not affect the function of the code, it cannot tolerate the red error.

This is generally a fixed writing method, which can be used to solve the above problems.

// 先把VueRouter原型对象的push,先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
 
// 重写push|replace
// 第一个参数:告诉原来push方法,你往哪里跳转(传递哪些参数)
// 第二个参数:成功的回调
// 第三个参数:失败的回调
//  call || apply区别
//  相同点,都可以调用函数一次,都可以篡改函数的上下文一次
//  不同点:call与apply传递参数:call传递参数用逗号隔开,apply方法执行,传递数组
VueRouter.prototype.push = function (location, resolve, reject) {
    
    
  if (resolve && reject) {
    
    
    originPush.call(this, location, resolve, reject);
  } else {
    
    
    originPush.call(this, location, () => {
    
    
    }, () => {
    
    
    })
  }
}
 
VueRouter.prototype.replace = function (location, resole, reject) {
    
    
  if (resole && reject) {
    
    
    originReplace.call(this, location, resole, reject);
  } else {
    
    
    originReplace.call(this, location, () => {
    
    
    }, () => {
    
    
    })
  }
}

Split of three-level linkage components

The third-level linkage component will be used in Home, Search, Detail and other components, and it can be made into a public global component TypeNav.

Insert image description here

After importing the static resources with reference to the Header component, register it main.jsas a global component. The advantage is that it can importbe used anywhere in the project without any need. The Header was imported before because it was not main.jsregistered as a global component.

// 三级联动全局组件
import TypeNav from '@/components/TypeNav';
// 注册为全局组件 arg1: 组件名称 arg2: 当前组件
Vue.component(TypeNav.name,TypeNav)

Then, we <TypeNav/>can register it in the index.vue of the Home component.

Insert image description here
Then we can follow the previous steps to split the remaining pages of the homepage into components for registration:

Insert image description here

Import these components and register them:

Insert image description here

appendix

The last screenshot information displayed is this:

![(https://img-blog.csdnimg.cn/06c32e2630c54795839b225caccf24ae.png)

Insert image description here
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_41857955/article/details/133420800