Vue2 e-commerce front-end project - project initialization and construction

Vue2 e-commerce front-end project - project initialization and construction

Click here for Vue basics - Vue.js

1. Project initialization

Use scaffolding to create a project, open cmd input in the directory where the project needs to be placed:

vue create name
  • This name is the project name (my project name is potato-mall

Create scaffolding configuration notes for specific references you have questions about or are unfamiliar with

1. Introduction to scaffolding catalog

After the project is successfully created, click on the project directory and the following files will appear:

Please add image description

These files are described below:

node_modules folder : Place project dependencies

Public folder : Generally, static resources (pictures) are placed. Note that when webpack packages static resources in the public folder, they will be packaged intact into the dist folder and will not be packaged as a module. into JS

src folder (programmer source code folder):

  • assets folder : generally placed static resources (generally placed static resources common to multiple components), please note: when webpack packages resources placed in the assets folder, the static resources will be treated as a module and packaged into Inside the JS file

  • components folder : Generally placed are non-routing components (global components)

  • App.vue : The only root component, all components in Vue are (.vue)

  • main.js : The entry file of the program and the first file to be executed in the entire program

babel.config.js : configuration file, related to babel

package.json file : project "ID card", records project information, what is it called...what are the dependencies...how does the project run...

package-lock.json : cacheable file

README.md : Descriptive file

2. Other configurations of the project

(1) When the project is running, automatically open the browser

Find the package.json file, find "scripts" and modify it as follows:

"scripts": {
    
    
    "serve": "vue-cli-service serve --open",  //在后面加“--open” 运行时自动打开浏览器
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
},

(2) The eslint syntax verification function is turned off.

It can be turned off or not. If it is turned on, an error will be reported but it will not affect the running of the code.

In the root directory, create a vue.config.js file (usually this file comes with when creating a project), and add the following code:

const {
    
     defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
    
    
  transpileDependencies: true,
  //关闭eslint语法校验
  lintOnSave: false,
});

(3) src folder abbreviation method, configure alias.

in the jsconfig.json file. @ represents the src folder, which will make it easier to find if there are too many files in the future.

2. Project routing analysis and construction

1. Project routing analysis

The so-called routing on the front end: key-value pair

key: URL (path in the address bar)

value: corresponding routing component

Project structure: top, middle and bottom structure

Non-routing components: Header,Footer(首页,搜索页)

Routing components: Home首页, Search搜索, login登录(无Footer),register注册(无Footer,可以通过条件渲染控制)

2. Steps to develop a project

  1. Write static pages (HTML, CSS)

  2. Split components (routed/non-routed)

  3. Get dynamic display of server data

  4. Complete the corresponding dynamic business logic

Note 1: When creating a component, find out the component structure + component style + image resources.
Note 2: If the project uses the less style, the browser does not recognize the less style, and needs to be processed through less and less-loader [install six versions] less: npm i less-loader@6. If you want the component to recognize the less style, you need to add lang="less" to the style tag. (If less still reports an error when running, you can try closing the project and re-entering to re-run the above installation command)
Note 3: Introduce the clear default style, place the default style file in the public folder, and introduce it in index.html.

3. Construction of non-routing components

Non-routing components are generally written in the components folder. This project has Header and Footer.

Component usage steps:

  1. Create or define components

  2. Introduce components

  3. Register component

  4. Use components

Please add image description

4. Construction of routing components

(1) Configure and use the router

Vue2 installs vue-router, command: npm i vue-router@3
Vue3 installs vue-router, command:npm i vue-router

We have already learned about it before. For details, please check the notes - basic knowledge and use of routing.

There are four routing components: Home, Search, Login, and Register.

componentsFolder: where non-routing components are often placed (public global components)
pages| viewsFolder: where routing components are often placed

The routes configured in the project are generally placed in the router folder, and the routes are configured in it.

Use <router-view></router-view>designated placements, then log in, register, and search for these a tags router-linkand hrefreplace them with tags.to

Please add image description

(2) What is the difference between routing components and non-routing components?

  1. Routing components are generally placed in the pages|views folder, and non-routing components are generally placed in the components folder.

  2. Routing components generally need to configure routing rules in the index.js file in the router folder (using attributes such as path and component name). When non-routing components are used, they are generally used in the form of labels.

  3. After registering the route, whether it is a routing component or a non-routing component, there will be route, route,ro u t e , router attribute
    route: generally obtain routing information [path, query, params, etc.], in fact, this among non-routing components. route: generally obtain routing information [path, query, params, etc.], in fact, non-routing this in the component.ro u t e : Generally obtain routing information [path, query , params , etc. ]. In fact, thi s . route among non-routing components is some information of the currently displayed routing component, such as path, name , meta, etc.
    $router: generally perform programmatic navigation for routing jumps [push | replace]

(3)Redirect

When the project is running, visit / and it will immediately direct him to the home page and write it in src/router/index.jsthe file.

Please add image description

(4) Two ways of route jump

  1. Declarative navigation router-link

  2. Programmatic navigation push | replace

Programmatic navigation can do everything that declarative routing navigation can do. In addition, programmatic navigation can also do some other services.

These two routing jump methods are mentioned in the previous notes, and there are case descriptions. For details, click here - Programmatic Routing Navigation

  • If it is just route jump and no other business logic, use declarative navigation router-link

Please add image description

  • If other business logic is required when routing, such as passing parameters, programmatic navigation can be used.

The search button here needs to be routed with the input information in the search box, using programmatic navigation:

Please add image description

Note: When using programmatic navigation, clicking the search button here multiple times may cause an error to occur during repeated navigation. You can add a method to capture exceptions every time it is called, or you can add the following code to route/index.js to solve the problem. The principle of this problem is to rewrite the push and replace methods on the Router prototype chain, use call to change this pointer, and throw an exception.

let originPush =  VueRouter.prototype.push;  //备份原push方法
 
VueRouter.prototype.push = function (location, resolve, reject){
    
    
    if (resolve && reject) {
    
        //如果传了回调函数,直接使用
        originPush.call(this, location, resolve, reject);
    }else {
    
                         //如果没有传回调函数,手动添加
        originPush.call(this, location, ()=>{
    
    }, ()=>{
    
    }); 
    }
}

3. Display and hiding of Footer component - routing meta information

Show or hide components: v-if / v-show
The Footer component is displayed in Home and Search, and is hidden in Login and Register.
We can $route.pathcontrol the display and hiding of Footer according to whether it is home or search.

<Header></Header>
<!-- 路由组件出口 -->
<router-view></router-view>
<!-- 在Home、Search显示,其他隐藏 -->
<Footer
	v-show="$route.path === '/home' || $route.path === '/search'"
>
</Footer>

But what if there are many components that need to display Footer? You have to write a lot, which is not good.

this.$routeIt stores the routing information under the current page path. We can use the meta attribute, that is路由元信息

Please add image description
Please add image description

4. Routing parameters

params and query parameters can be passed together

1. Review the two methods of routing jumps

Declarative navigation: router-link (must have to attribute)

Programmatic navigation: using the $router.push | replace method of the component instance

2. When passing parameters in a route, how many ways are there to write parameters?

Parameters include params parameters and query parameters respectively. For details, please click here - Routing Parameter Passing

query参数:/home?k=v&kv=, no space required

params参数: When configuring routing, it is necessary to occupy space

Please add image description

When routing carries paramsparameters, if it is used to, 对象写法configuration pathitems cannot be used and nameconfiguration must be used! And params need to occupy space!

3. Routing parameter transfer review questions (⭐)

  1. Route passing parameters (object writing) Can path be used in conjunction with the params parameter?

    Can't. When passing parameters in a route jump, the object can be written in the form of name or path, but it should be noted that the writing method of path cannot be used together with the params parameter.

  2. How to specify whether the params parameter can be passed or not?
    When configuring routing, add ? after the params placeholder, indicating that it can be passed or not.

Please add image description

For example: when configuring the route, if the params parameter has been occupied but no question mark is written, then the params parameter will not be passed when the route jumps, and problems will occur in the path. The location you jumped to was originally http://localhost:8080/#/search/k=QWE. However, the location you jumped to was http://localhost:8080/#/k=QWE. The search path was not there. No, this won't work

  1. The params parameter may or may not be passed, but if it is an empty string, how to solve it?

    If there are placeholders and question marks, but an empty string is passed, there will be problems with the path (same as the path problem above, the search will disappear)

    Use undefined to solve the problem: when the params parameter is passable but not passable, the empty string path is passed.

  params:{
    
    
            keyWord:'' || undefined,
          },
  1. Can routing components pass props data?
    Yes, there are three ways to write it: object, Boolean, and functional. For details, see the props configuration in the routing notes.

5. Solve bugs

If programmatic routing jumps to the current route (the parameters remain unchanged), will a NavigationDuplicated warning error be thrown if executed multiple times?

Because there are two forms of route jumps: declarative navigation and programmatic navigation. Declarative navigation does not have such problems because the bottom layer of vue-router has already been handled.

Why does this warning error appear when programmatic navigation performs routing jumps?

1. "vue-router": "^3.6.4": The latest vue-router introduces promise. Push returns promise. Promise has two formal parameters, a function returned successfully and a function returned failed.

By passing the corresponding success and failure callback functions through the push method, the current error can be captured and resolved.

The error can be solved with the following code

this.$router.push({
    
    
          // 第三种:对象写法
          name:'sousuo',
          // params参数
          params:{
    
    
            keyWord:'' || undefined,
          },
          // query参数
          query:{
    
    
            k:this.keyWord.toUpperCase()
          }
        },()=>{
    
    },()=>{
    
    })

This writing method treats the symptoms but not the root cause. In the future, push | replace and programmatic navigation will still have similar errors in other components.
Since this is a component and $router is an instance of VueRouter, it can access the push on the VueRouter prototype object, so we By rewriting the push method, the problem can be solved. (mentioned above)

// 以下代码在src/router/index.js文件中

//重写push和replace解决重复点击报错的问题
//先把VueRouter原型对象的push和replace,先保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.Replace
//重写push|replace方法
//第一个参数location:告诉原来push方法,往哪里跳转(传递哪种参数)
//第一个参数resolve:成功的回调
//第三个参数reject:失败的回调
VueRouter.prototype.push = function(location,resolve,reject){
    
    
    if(resolve && reject){
    
    
        //call||apply:相同点:都可以调用函数一次,都可以篡改函数的上下文一次
        //不同点:call与apply传递参数:call传递参数多个参数用逗号隔开,而apply方法执行要传递数组
        //调用originPush,把this指向push的调用者
        originPush.call(this,location,resolve,reject)
    }else{
    
    
        originPush.call(this,location,()=>{
    
    },()=>{
    
    })
    }
}
//第一个参数:告诉原来replace方法,往哪里跳转(传递哪种参数)
VueRouter.prototype.replace = function(location,resolve,reject){
    
    
    if(resolve && reject){
    
    
        originReplace.call(this,location,resolve,reject)
    }else{
    
    
        originReplace.call(this,location,()=>{
    
    },()=>{
    
    })
    }
}

Guess you like

Origin blog.csdn.net/weixin_56498069/article/details/132723003