Test results blog

This blog environment

If these outdated environment, then do not waste the time to read this blog

Vue-Cli project environment to build

npm (just like a mobile phone application store, python in the pip, too)

Contrast with basic environmental python

  1. Node ~ Python interpreter
    • node is js interpreter, written with c ++
  2. npm ~ PIP Python library management tool (third-party modules to download app store)
    • npm is similar to pip, must change the source (common source Taobao cnpm), download it fast
  3. view ~ django
    • Django is like a big frame

Environment to build

  • Installation node
node 官网下载安装包,傻瓜式安装:https://nodejs.org/zh-cn/

The following commands are executed from the command line ( -gparameter represents the global (global), will automatically configure the environment variables)

  • Installation CNPM (using Taobao mirror source)

    npm is a node that comes with the package manager, cnpm Taobao mirror source (npm can be seen as a domestic version), download third module will be much faster than npm (foreign warehouse to the next), almost all the places you can use npm replaced by cnpm

npm install -g cnpm --registry=https://registry.npm.taobao.org
  • Install scaffolding tool vue / cli
cnpm install -g @vue/cli
  • Empty the cache processing ( the first two steps wrong and then execute this (to delete those files download errors))
npm cache clean --force

Create a project started vue

We must pay attention to the current directory location of the command line

Webstorm vue can be written in the code developed specifically for the front end, and the tips PyCharm convenience it is better (self-learn)

Command to create a project (multi-step small)

First to enter the directory to store project

cd /d E:\PyCharm 2019.1.3\ProjectFile\day010\day066 (Day66 project will be placed in this folder)

Create a project

vue create v-proj(项目名) , After input will enter into the following interface

Interface operation mode: down the keyboard (↑ ↓) to use the arrow keys to select a template, the selected carriage (the same interface into the underlying arrow to move the cursor up and down, press the space bar to select, Confirm)

We chose the following Manually select features

Came to the following page, take a look at these options do you mean

Each option

  • Babel
    • ES6 converted into ES5 syntax allows the browser can resolve
  • TypeScript
    • JavaScript is a superset (it will be harder to learn than JavaScript)
  • Progressive Web App (PWA) Support
    • There are many components to optimize the reception of the project (and then to the late)
  • Router
    • vue front desk routing management
  • Vuex
    • The equivalent of a global singleton, refresh the page is not valid, a refresh is gone
  • CSS Pre-processors
    • less, sass -> pre-compiled language, is written in css, but it can write logic must be resolved to the native browser css to be useful, relatively speaking will be a little less eager to learn, you can learn about two hours
  • Linter / Formatter
    • Limit (team) coding style (indent number of spaces and the like) ESLint more stringent
  • Unit Testing
    • Test of
  • E2E Testing
    • Test of

We selected the following several (box selected)

Enter the next step (re-election all the way to the capital on the line)

When the page history so that the application vue can jump so far (the other being the default can)

The default configuration is as follows

Then it will automatically install

So far, vue project created

Start vue project (command line)

At the command line, enter the project root directory, execute npm run servethe startup project

After waiting for loading, appears in the following page to enter the browser localhost:8080access (vue project is the default port 8080)

Access on the browser

Start vue project (pycharm way)

Command line to start with a lot of inconvenience, so we chose to adopt pycharm to start it (in fact webstorm support vue will be better , but not the point here), the following is pycharm start to do some configuration

Right before the project folder and open with pycharm

Configuration pycharm start

Vue project started with the green start button pycharm

Page effect (At this point, pycharm to start the project)

Vue project directory structure analysis

├── v-proj
|   ├── node_modules    // 当前项目所有依赖,一般不可以移植给其他电脑环境(版本控制、备份代码 等等,这个文件一般都排除在外),在新环境下执行 cnpm install 即可重新安装下载这个文件里的内容
|   ├── public          
|   |   ├── favicon.ico // 浏览器标签页图标(public/index.html 中的 <link rel="icon" href="<%= BASE_URL %>favicon.ico">)
|   |   └── index.html  // 当前项目唯一的页面
|   ├── src
|   |   ├── assets      // 用来存放静态资源,如:img、css、js
|   |   ├── components  // 存放小组件(再老一些的版本 components 和 views 是一个文件夹)
|   |   ├── views       // 存放页面组件(一般是路由跳转的组件)
|   |   ├── App.vue     // 根组件
|   |   ├── main.js     // 全局脚本文件(项目的入口)
|   |   ├── router.js   // 路由脚本文件(配置路由 url链接 与 页面组件的映射关系)
|   |   └── store.js    // 仓库脚本文件(vuex插件的配置文件,数据仓库)
|   ├── README.md
└   └── **配置文件...

// "├" 输入法 "v9" 可以找到这个符号

pycharm support vue grammar

Vue plug-in installation

Double-click App.vue can see, there is no syntax highlighting, .vue file is identified became a regular file, then we can install plug-vue to solve this problem

Can point to install plugins in FIG vue mounting plug (according to the installation prompts)

You can also download the settings pycharm's, you can download the complete restart pycharm

After the restart pycharm, pycharm able to identify .vue files, and can provide us with syntax highlighting (immediate and instant full color)

Vue file analysis section

And custom components to render the page

Component files in the following components, usually capitalized

Assembly generally consists of the following three parts

  1. template
    • Inside there is one and only one root tag
  2. script
    • You must be {}exported (to export to the outside world in order to import)export default
    • When introduced into the outside world, it will be {}assigned to the front of the variable (associate)
  3. style
    • style tags must be explicitly scoped attribute, representing the style only work (assembly of styles) in internal components

Import and export assembly

Write the code in some places a red wavy line may be ESLint error, a variable will not use this, then write down just fine, not too tight

The export component (exposed)

Components need to be an example? (Looked like a content-rich vue example) export, the outside world in order to use

src/components/Test.vue

<template>
<!--    template 里只能有一个根标签(作为一个组件)-->
    <div class="test">
        <p>Test 组件</p>
    </div>
</template>

<script>
    // 需要将其导出,外界才能导入,这个括号相当于一个 vue 实例
    export default {
        name: "Test"
    }
</script>

<style scoped>
    /* style 里面的这个 scoped 可以用来限制样式的控制范围(仅对这个组件生效)(让样式局部化,避免造成 css 冲突)*/
    p {
        color: red
    }
</style>

Introducing parent component (exposed) component

src / views / TestViews.vue

<template>
    <div class="home">
        <!-- 3. 直接在页面上渲染自定义标签(在 .vue 结尾的文件中标签可以区分大小写(不像 html 文件,不能区分标签的大小写))-->
        <T></T>  <!-- 到时候子组件会直接把这个替换掉 -->
    </div>
</template>

<script>
    // 1. 将组件导入,并赋值给 T (把子组件 export default 那个实例? 跟 变量T ? 关联起来,在本(父)组件中就可以直接用 T 来当 Test 组件操作了)
    import T from '@/components/Test'
    // 这个 @ 就等价于 src 文件夹的绝对路径

    export default {
        // 2.注册组件
        components: {
            T, // 注册 T 组件
        }
    }
</script>

Configuring Routing in routers.js

src/router.js

The address bar will have no history # id ( localhost:8080/#/路由)

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
// ****** 1. 先导入 ******
import Test from './views/TestViews'

Vue.use(Router)

export default new Router({
  mode: 'history',  // 让 vue 这种单页面应用也支持 浏览器的前进后退(← →) (可以展开搜索下)
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    },
    // ****** 2. 注册一条路由 ******
    {
      path: '/test',  // ****** 3. 一会儿直接访问这个路由即可 localhost:8080/test ******
      name: 'test',
      component: Test
    }
  ]
})

Browser access

localhost:8080/test

Why have the page Home | About what? We have just not any write

Why have the page Home | About what? - is actually the root component App.vuewhich wrote

src / App.vue (see inside Home, |, About)

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

Main.js global script file parsing (Project entrance)

Generally, when imported suffix will be omitted so as not to the same folder under the same name (import negligible suffix)

The default wording (vue project to create an automatically generated)

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// 新手教程的 使用提示 (要点 next next 的动画)
Vue.config.productionTip = false

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')  // 等同于 el 挂载

Explanatory wording us more able to understand the wording of (the equivalent of just the interpretation of the above)

import Vue from 'vue'  // 加载vue环境
import App from './App.vue'  // 加载根组件
import router from './router'  // 加载路由环境
import store from './store'  // 加载数据仓库环境

Vue.config.productionTip = false

new Vue({
    el: '#app',
    router,
    store,
    render: function (readFn) {
        return readFn(App);
    },
});

vue start of the project life cycle

Load Startup Items mian.js

  • import Vue from 'vue' Load vue environment for the project
  • import App from './App.vue' Loading the root component mount point for rendering the replacement
  • import router from './router' Load routing script file, enter the route configuration

Load router.js file

Provides routing services for the project, and load routing (mapping between links and page assembly) configured

Note: No matter what the route is currently rendering, page rendering must be the root component, linked to the matching page components just replace the root assembly<router-view></router-view>

Monitor routing changes done deal

Principle page jump occurred vue

If (route change) request link changed, Router was matched, and the corresponding components will route out, and then the root component in the <router-view></router-view>replacement tags into the component

  • Each time the route will take the time to jump component life cycle

Participate file

main.js entry file

The content of the document unchanged

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')

App.vue project root component

Root component of common items (App.vue) only wrote the following lines of code

<template>
    <div id="app">
        <!-- url路径会加载不同的页面组件
            eg:/red => RegPage  | /blue => BluePage
         来替换router-view标签,完成页面的切换
         -->
        <router-view></router-view>
    </div>
</template>

views / RedPage.vue custom page components

<template>
    <div class="red-page">
        
    </div>
</template>
<script>
    
    export default {
        name: "RedPage",
        components: {
            
        },
    }
</script>
<style scoped>
    .red-page {
        width: 100vw;
        height: 100vh;
        background-color: red;
    }
</style>

views/BluePage.vue

<template>
    <div class="blue-page">
        
    </div>
</template>
<script>
    
    export default {
        name: "BluePage",
        components: {
            
        }
    }
</script>
<style scoped>
    .blue-page {
        width: 100vw;
        height: 100vh;
        background-color: blue;
    }
</style>

router.js routing file

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import RedPage from "./views/RedPage";
import BluePage from "./views/BluePage";

Vue.use(Router);

export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/red',
            name: 'red',
            component: RedPage
        },
        {
            path: '/blue',
            name: 'blue',
            component: BluePage
        }
    ]
})

The global style configuration file and application

jQuery, BootStrap the external environment, the need to fit in at main.js

The latter may be written as a path to configure these profiles

assets/css/global.css

/*html, body, h1, h2, ul, p {*/
*{
    margin: 0;
    padding: 0;
}
ul {
    list-style: none;
}
a {
    color: black;
    text-decoration: none;
}

main.js import, let it take effect

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

// ********* 配置全局样式 *********
import '@/assets/css/global.css'


// new Vue({
//     router,
//     store,
//     render: h => h(App)
// }).$mount("#app");

new Vue({
    el: '#app',
    router,
    store,
    render: function (readFn) {
        return readFn(App);
    },
});

Small Case - Nav navigation bar component package

components / Nav.vue new subassembly

Using a label refresh the page jump happens, reload a project interface

-> The vue is a single-page application, usually <router-link to="/路由"> </router-link>the process jumps

  • Each time the route will take the time to jump component life cycle
<template>
    <div class="nav">
        <!--采用 vue-router 完成页面跳转,不能采用 a 标签(会发生页面刷新,本质就是重新加载了一次项目界面)-->
        <ul>
            <li>
                <!--<a href="/">主页</a>-->
                <router-link to="/">主页</router-link>
            </li>
            <li>
                <router-link to="/red">红页</router-link>
            </li>
            <li>
                <router-link to="/blue">蓝页</router-link>
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Nav",
    }
</script>

<style scoped>
    .nav {
        width: 100%;
        height: 60px;
        background-color: orange;
    }
    .nav li {
        float: left;
        font: normal 20px/60px '微软雅黑';
        padding: 0 30px;
    }
    .nav li:hover {
        cursor: pointer;
        background-color: aquamarine;
    }
    .nav li.active {
        cursor: pointer;
        background-color: aquamarine;
    }
</style>

views / HomePage.vue New View page

RedPage.vue with three steps below BluePage codes are added

<template>
    <div class="home">
        <!-- 3)使用Nav组件 -->
        <Nav></Nav>
    </div>
</template>

<script>
    // 1)导入Nav组件
    import Nav from '@/components/Nav'
    export default {
        // 2)注册Nav组件
        components: {
            Nav,
        }
    }
</script>

New three-step page

  1. Create a view component in the views folder (.vue file)
  2. Configuring a Route router.js file
  3. Route setting jump, the page rendering component (router-view replace the root tag assembly) at a specified route
    • Render who, (router-view) who would replace

Case

Add a tan page Case Code

views / TanPage.vue

<template>
    <div class="tan-page">
        <Nav></Nav>
    </div>
</template>

<script>
    import Nav from '@/components/Nav'
    export default {
        name: "TanPage",
        components: {
            Nav
        }
    }
</script>

<style scoped>
    .tan-page {
        width: 100vw;
        height: 100vh;
        background-color: tan;
    }
</style>

router.js

// ...
import TanPage from "./views/TanPage";
export default new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        // ...
        {
            path: '/tan',
            name: 'tan',
            component: TanPage
        }
    ]
})

components / Nav.vue

...
<li>
    <router-link to="/tan">土页</router-link>
</li>
...

Component Life Cycle (hook function analysis)*****

basic concepts

Details can be seen vue official API (recommended a good look at the official presentation of this document)

The life cycle of components: a component process from creation to destruction, it is called the life cycle of components

In the assembly process of creation to destruction , there will be a number of time-critical node, such as:

  • To create a component
  • Components to create finished
  • Rendering finished component data
  • Components to be destroyed
  • The destruction of finished components
  • ... and so time node

Each time a node, all VUE to provide a callback function (at the time of the arrival node assembly, triggers the corresponding callback function, the function can be completed in the service logic node needs to be done )

Lifecycle hook function is an instance of a member of vue

Lifecycle hook function

vue official lifecycle hook function

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
activated
deactivated
beforeDestroy
destroyed
errorCaptured

Direct write the hook function in the script of export vue components default Exporting dictionary

Key hook function: the Created (to use other functions on demand)

The general background component data request, the hooks are done in

  1. Data requests can be assigned to the variable page (At this instance members already loaded)
  2. The node just stop at the virtual DOM category, if the data needs to be done to render the page and then modify secondary
  3. Logic may be added in beforeMount, mounted hooks
export default {
    // ...
    beforeCreate() {
        console.log('组件创建了,但数据和方法还未提供');
        // console.log(this.$data);
        // console.log(this.$options.methods);
        console.log(this.title);
        console.log(this.alterTitle);
    },
    // 该钩子需要掌握,一般该组件请求后台的数据,都是在该钩子中完成
    // 1)请求来的数据可以给页面变量进行赋值
    // 2)该节点还只停留在虚拟 DOM 范畴,如果数据还需要做二次修改再渲染到页面,
    //  可以在beforeMount、mounted钩子中添加逻辑处理
    created() {
        console.log('组件创建了,数据和方法已提供');
        // console.log(this.$data);
        // console.log(this.$options.methods);
        console.log(this.title);
        console.log(this.alterTitle);
        console.log(this.$options.name);
    },
    destroyed() {
        console.log('组件销毁完毕')
    }
}
  • this.$options You can get all instances members, including custom member (like make vue members of these instances is loaded in advance), a bunch of these properties are in there (you can use it to define attributes from)
  • Examples vue directly this.属性/方法accessible to members of the Data instances, methods of content (made package, can get directly)

  • vue no this.$methodthis member properties

The request path routing label case highlighted

<router-link to="/">主页</router-link>

  • router-link will ultimately be resolved to a label, with a jump to the completion of the specified path, but can not add system events (as is the tag component)
  • Js used in the process may this.$router.push('路径')complete logic jumps
  • Js used in the process may this.$route.pathget the current page request routing

components / Nav.vue

this.$route、this.$router You can take a look (search it), a routing data management, a management routing Jump

<template>
    <div class="nav">
        <!--采用vue-router完成页面跳转,不能采用a标签(会发生页面刷新,本质就是重新加载了一次项目界面)-->
        <ul>
            <li @click="changePage('/')" :class="{active: currentPage === '/'}">
                <!--<a href="/">主页</a>-->
                <!--<router-link to="/">主页</router-link>-->
                主页
            </li>
            <li @click="changePage('/red')" :class="{active: currentPage === '/red'}">
                <!--<router-link to="/red">红页</router-link>-->
                红页
            </li>
            <li @click="changePage('/blue')" :class="{active: currentPage === '/blue'}">
                <!--<router-link to="/blue">蓝页</router-link>-->
                蓝页
            </li>
            <li @click="changePage('/tan')" :class="{active: currentPage === '/tan'}">
                <!--<router-link to="/tan">土页</router-link>-->
                土页
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Nav",
        data() {
            return {
                // 每渲染一个页面,都会出现加载 Nav 组件,currentPage 就会被重置,
                // 1)在点击跳转事件中,将跳转的页面用 数据库 保存,在钩子函数中对 currentPage 进行数据更新
                // currentPage: localStorage.currentPage ? localStorage.currentPage: ''
                // 2)直接在 created 钩子函数中,获取当前的 url 路径,根据路径更新 currentPage
                currentPage: ''
            }
        },
        methods: {
            changePage(page) {
                // console.log(page);
                // 当 Nav 出现渲染,该语句就无意义,因为在 data 中将 currentPage 重置为空
                // this.currentPage = page;

                // 有 bug,用户不通过点击,直接修改请求路径完成页面跳转,数据库就不会更新数据
                // localStorage.currentPage = page;

                // 任何一个标签的事件中,都可以通过 router 完成逻辑条件
                // console.log(this.$route);  // 管理路由数据
                // console.log(this.$router);  // 管理路由跳转
                this.$router.push(page);  // 路由的逻辑跳转
            }
        },
        // 当前组件加载成功,要根据当前实际所在的路径,判断单选激活标签
        created() {
            // console.log(this.$route.path);
            this.currentPage = this.$route.path;
        }
    }
</script>

<style scoped>
    .nav {
        width: 100%;
        height: 60px;
        background-color: orange;
    }
    .nav li {
        float: left;
        font: normal 20px/60px '微软雅黑';
        padding: 0 30px;
    }
    .nav li:hover {
        cursor: pointer;
        background-color: aquamarine;
    }
    .nav li.active {
        cursor: pointer;
        background-color: aquamarine;
    }
</style>

Component life cycle chart vue official offer

Guess you like

Origin www.cnblogs.com/suwanbin-thought/p/11689902.html