Vue and Vue-Element-Admin (1): Vue foundation and framework

The current project involves data warehouse/front-end display after analysis. It is developed based on the mature front-end framework of vue-element-admin. It is an open source technical solution of vue+element ui: vue-element-admin code cloud address , Tutorial: vue-element-admin tutorial , the interface is simple and refreshing;

The technology stack involved in Vue-element-admin includes vue, vuex, vue-router, vue-cli, axios, element-ui, so the vue framework itself (vue, vuex, vue-router, vue- cli, axios), and vue-element-admin;

Vue foundation and framework

Understanding of MVC and MVVC

According to the previous popular MVC framework, the view layer completes the definition of data visualization. Assuming that the front and back ends realize the display of the student class, the steps required are: ① The bean class of Student, which is the model, realizes the definition of multiple properties and methods of Student; ② StudentController controller, which defines the front-end data request body (spring uses RuquestMapping annotation); ③ Create view viewer, according to the way of mybatis framework, first define the query interface StudentMapper (define query sql naming and return type), and the static with the same name StudentMapper.xml file (encapsulate sql conditional query statement);

The advantages of MVC are low coupling, high reusability, and high maintainability. The advantages are also disadvantages, which increase the complexity of the system structure and implementation. For simple interfaces, strictly follow MVC and separate the model, view and controller, which will increase the complexity of the structure, and may generate too many update operations and reduce operating efficiency.

The front and back ends are separated using the MVVM framework (Model-View-ViewModel) two-way data binding , the core of which is the ViewModel layer, and the view model layer is the bridge between View and Model. On the one hand, it implements Data Binding, that is, data binding, which reflects the changes of Model to the View in real time. On the other hand, it implements DOM Listener, which is DOM monitoring. When some events (click, scroll, touch Etc.), you can listen to it and change the corresponding Data if necessary.

 

Introduction and demo of vue

Vue rookie tutorial . Vue is a js framework that allows developers to declaratively bind the DOM to the data of the underlying Vue instance. In the underlying implementation, Vue compiles the template into a virtual DOM rendering function. Combined with the response system, Vue can calculate intelligently There are many ways to install Vue to determine the minimum number of components that need to be re-rendered and minimize the number of DOM operations:

1. You can choose to introduce a development environment version or a production environment version

<!-- 开发环境版本,包含了有帮助的命令行警告 --> 
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

2. Download and import

开发环境 https://vuejs.org/js/vue.js 
生产环境 https://vuejs.org/js/vue.min.js

 3. NPM installation: subsequent use through webpack and CLI

The simplest demo is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</ti	tle>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app-5">
  <p>{
   
   { message }}</p>
  <button v-on:click="reverseMessage">反转消息</button>
</div>

<script>
var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})
</script>
</body>
</html>

Vue contains some special tags, using v- as a prefix, such as:

v-if: Render the element according to the true or false condition of the value of the expression. When switching, the element and its data binding/component are destroyed and rebuilt. v-if control element rendering v-if is false, the element will not be created;

v-show: Switch the display CSS property of the element according to the true and false value of the expression. You can control the display and hide of the element through display none

v-for: loop instruction, based on an array or object to render a list, Vue 2.0 and above must be used with the key value. Bind a label to loop a data source array table number string

v-bind: dynamically bind one or more properties, or a component prop to an expression. The property is followed by a fixed string function: property binding allows the property to be followed by a variable or expression

v-on: Used to monitor DOM events of the specified element, such as click events. Bind event listeners. Event name='event processing function' The event name is the same as native JS

v-model: to achieve two-way binding between form input and application state. Equivalent to the synthesis of event binding v-on and attribute binding v-bind (aggregate)

v-pre: Skip the compilation process of this element and its child elements. Can be used to display the original Mustache tags. Skip a lot of nodes without instructions will speed up compilation

v-once: Only render the element and component once, and after re-rendering, the element/component and all its child nodes will be treated as static content and skipped. This can be used to optimize update performance

A very important feature of vue is: component-based building applications, you can use small, independent and usually reusable components to build large applications, such as li label template + v-for loop + vue component to complete data traversal;

<div id="app-7">
  <ol>
    <!--
      现在我们为每个 todo-item 提供 todo 对象
      todo 对象是变量,即其内容可以是动态的。
      我们也需要为每个组件提供一个“key”,稍后再
      作详细解释。
    -->
    <todo-item
      v-for="item in groceryList"
      v-bind:todo="item"
      v-bind:key="item.id"
    ></todo-item>
  </ol>
</div>

Vue.component('todo-item', {
  props: ['todo'],
  template: '<li>{
   
   { todo.text }}</li>'
})

var app7 = new Vue({
  el: '#app-7',
  data: {
    groceryList: [
      { id: 0, text: '蔬菜' },
      { id: 1, text: '奶酪' },
      { id: 2, text: '随便其它什么人吃的东西' }
    ]
  }
})

vue options (options)

A vue instance can define data, methods, props, computed, watch options about data;

data: The data object of the Vue instance

props: props can be arrays or objects, used to receive data from the parent component;

computed: compute attributes, used when the amount of data is large and needs to be cached;

Methods: calculation method, used when no cache is needed (such as time), called in the form of a function;

watch: an object, the key is the expression that needs to be observed, and the value is the corresponding callback function;

At the same time, Vue can also define some life cycle hook options, such as the need to set up data monitoring, compile templates, mount the instance to the DOM and update the DOM when the data changes.

title

Examples of test hook functions:

<!DOCTYPE html>
<html>
<head>
    <title>钩子函数</title>
    <meta charset="utf-8">
    <script src="http://cdn.bootcss.com/vue/2.1.10/vue.js"></script>
<body>

<div id="app">
    <p>{
   
   { message }}</p>
    <input type="button" @click="change" value="更新数据" />
    <input type="button" @click="destroy" value="销毁" />
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            message : "Welcome Vue"
        },
        methods:{
            change() {
                this.message = 'Datura is me';
            },
            destroy() {
                vm.$destroy();
            }
        },
        beforeCreate: function () {
            console.group('beforeCreate 创建前状态===============》');
            console.log("%c%s", "color:red","el     : " + this.$el); //undefined
            console.log("%c%s", "color:red","data   : " + this.$data); //undefined
            console.log("%c%s", "color:red","message: " + this.message);//undefined
        },
        created: function () {
            console.group('created 创建完毕状态===============》');
            console.log("%c%s", "color:red","el     : " + this.$el); //undefined
            console.log("%c%s", "color:green","data   : " + this.$data); //[object Object]  =>  已被初始化
            console.log("%c%s", "color:green","message: " + this.message); //Welcome Vue  =>  已被初始化
        },
        beforeMount: function () {
            console.group('beforeMount 挂载前状态===============》');
            console.log("%c%s", "color:green","el     : " + (this.$el)); //已被初始化
            console.log(this.$el); // 当前挂在的元素
            console.log("%c%s", "color:green","data   : " + this.$data); //已被初始化
            console.log("%c%s", "color:green","message: " + this.message); //已被初始化
        },
        mounted: function () {
            console.group('mounted 挂载结束状态===============》');
            console.log("%c%s", "color:green","el     : " + this.$el); //已被初始化
            console.log(this.$el);
            console.log("%c%s", "color:green","data   : " + this.$data); //已被初始化
            console.log("%c%s", "color:green","message: " + this.message); //已被初始化
        },
        beforeUpdate: function () {
            alert("更新前状态");
            console.group('beforeUpdate 更新前状态===============》'); //这里指的是页面渲染新数据之前
            console.log("%c%s", "color:green","el     : " + this.$el);
            console.log(this.$el);
            console.log("%c%s", "color:green","data   : " + this.$data);
            console.log("%c%s", "color:green","message: " + this.message);
            alert("更新前状态2");
        },
        updated: function () {
            console.group('updated 更新完成状态===============》');
            console.log("%c%s", "color:green","el     : " + this.$el);
            console.log(this.$el);
            console.log("%c%s", "color:green","data   : " + this.$data);
            console.log("%c%s", "color:green","message: " + this.message);
        },
        beforeDestroy: function () {
            console.group('beforeDestroy 销毁前状态===============》');
            console.log("%c%s", "color:red","el     : " + this.$el);
            console.log(this.$el);
            console.log("%c%s", "color:red","data   : " + this.$data);
            console.log("%c%s", "color:red","message: " + this.message);
        },
        destroyed: function () {
            console.group('destroyed 销毁完成状态===============》');
            console.log("%c%s", "color:red","el     : " + this.$el);
            console.log(this.$el);
            console.log("%c%s", "color:red","data   : " + this.$data);
            console.log("%c%s", "color:red","message: " + this.message)
        }
    })
</script>
</body>
</html>

Componentization of vue

Componentization is an important idea in Vue.js. It provides an abstraction to develop independent and reusable small components to construct applications. Any application will be abstracted into a component tree, which is generally defined by template. Components:

In the component, use the option props to declare the data that needs to be received from the parent. Sometimes it is necessary to access data between the parent component and the child component. For example, when the parent page and the child page jump, the parent component accesses the child component. $children or $refs, the child component accesses the parent component using $parent;

 

Parent-child data transfer

vue slot slot

     Many front-end components have many differences, but they also have many commonalities. How to encapsulate such components? (Extract the commonalities and keep the differences). The reserved slot allows the user to decide what to insert in the slot according to their needs, whether it is a search box, text, or menu, which is up to the caller to decide.

When the function of the sub-component is complex, the slot of the sub-component may not be one. For example, the sub-component encapsulating the navigation bar needs three slots on the left, middle, and right. You need to give the slot a name and give the slot element a name. Attribute: <slot name='myslot'></slot>

Modularity of vue

In the early days of web page development, js production was used as a scripting language to do some simple form verification or animation implementation. At that time, there was very little code. Just write the code directly in the <script> tag. With the emergence of ajax asynchronous requests The separation of front and back ends is slowly formed. There are more and more things that the client needs to complete, and the amount of code is increasing day by day. In order to cope with the sharp increase in the amount of code, the code is maintained in multiple js files, but this maintenance method still cannot Avoid some catastrophic problems, such as the problem of the same name of global variables. In addition, this way of writing code is almost mandatory for the dependency order of js files, but when there are too many js files, such as dozens of them, you need to figure it out Their order

Common modular specifications: CommonJS, AMD, CMD, and ES6 Modules. The two cores of modularization are export and import:

In some cases, a module contains a certain function, we do not want to name this function, and let the importer can name it himself, this time you can use export default (in the same module, it is not allowed to exist multiple A), in main.js, myFunc can name itself;

If you want to carry out modular development, you also need to deal with the various dependencies between modules, and integrate them into packaging, you must rely on other tools, webpack can carry out modular development and handle the dependencies between modules, not just JavaScript Files, CSS, images, json files, etc. can all be used as modules in webpack. This is the concept of modularization in webpack. Vue uses webpack’s modularity and configuration;

vue scaffolding vue-cli

Vue CLI must be used in the development of large projects, because it needs to consider things such as code directory structure, project structure and deployment, hot loading, code unit testing, etc. It is relatively inefficient to complete these tasks manually, so some scaffolding tools are usually used to help complete these things.

The full name of NPM is Node Package Manager, which is a NodeJS package management and distribution tool. It has become an unofficial standard for publishing Node modules (packages). Generally, NPM is used to install some dependent packages in the development process;

There is a big difference between vue-cli 3 and version 2. vue-cli 3 is based on webpack 4, vue-cli 2 or webapck 3; the design principle of vue-cli 3 is the root directory of the configuration file removed by "0 configuration" For directories such as build and config, vue-cli 3 provides the vue ui command, which provides a visual configuration, which is more user-friendly; the static folder is removed, the public folder is added, and index.html is moved to public;

Scaffolding 2
Scaffolding 3

 

npm run bulid
npm rum dev

vue state management vuex

Vuex is a state management mode specially developed for Vue.js applications. It uses centralized storage and management of the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner; state management can be simple Understand that the variables that need to be shared by multiple components are all stored in one object, and then this object is placed in the top-level Vue instance so that other components can use it;

In large-scale development tasks, multiple states need to be shared between multiple interfaces, such as the user's login status, user name, avatar, geographic location, product collection, items in the shopping cart, and so on. These status information can be placed in a unified place to save and manage it, and they are responsive;

First, create a folder store, and create an index.js file in it, write the following code in the index.js file:

Secondly, let all Vue components can use this store object, go to the main.js file, import the store object, and put it in new Vue, so that it can be obtained by this.$store in other Vue components store object:

Use the state saved in the store object in other components, access the state through the this.$store.state property, and modify the state through this.$store.commit('mutation method'). In this count example, pass Submit the mutation instead of directly changing store.state.count, because Vuex can track changes in state more clearly, without directly changing the value of store.state.count.

Vuex has several core concepts: State, Getters, Mutation, Action, Module. Vuex uses a single state tree to manage all the states of the application level. A single state tree can use the most direct way to find a fragment of a state, and In the subsequent maintenance and debugging process, it can also be very convenient to manage and maintain;

Mutation is the only way to update the state. Action is similar to Mutation, but it is used to perform asynchronous operations instead of Mutation;

Vuex allows the store to be divided into modules (Module), and each module has its own state, mutations, actions, getters, etc.

vue routing vou-router

Vue-router is the official routing plug-in of Vue.js. Vue.js is deeply integrated and suitable for building single-page applications. Routing is used to map paths and components;

Steps to use vue-router:
Step 1: Create routing components
Step 2: Configure routing mapping: component and path mapping relationship
Step 3: Use routing: Via <router-link> and <router-view>

 <router-link>: This tag is a built-in component in vue-router, it will be rendered as an <a> tag;

Vue's asynchronous request axios

Vue uses the axios library for back-end interaction to obtain data. It is a promise-based http library that can run on the browser side and node.js. It has many excellent features: intercepting requests and responses, canceling requests, converting json, and client defense , First referenced in the main entry file main.js, and then hung on the vue prototype chain;

Guess you like

Origin blog.csdn.net/yezonggang/article/details/109313711