current position:Home>Detailed explanation of Vue Foundation

Detailed explanation of Vue Foundation

2022-06-24 09:44:13Shuai dada's structural road

original text

vue Basic explanation

① Vue Overview and first Vue Program (Hello World)

1.1 What is? MVVM

MVVM(Model-View-ViewModel) It's a software design pattern , From Microsoft WPF( Used in substitution WinForm, This technology was used to develop desktop applications before ) and Silverlight( Be similar to Java Applet, Simply put, it's running on a browser WPF) Architect Ken Cooper and Ted Peters Development , It's an event driven programming that simplifies the user interface . from John Gossman( also WPF and Sliverlight Architect ) And 2005 Published on his blog in .

MVVM From the classic MVC(Model-View-Controller) Pattern .MVVM The core is ViewModel layer , Responsible for the conversion Model Data objects in to make data easier to manage and use . Its functions are as follows :

  • This layer carries out bidirectional data binding with the view layer upward
  • Down and Model Layer through the interface request data interaction
     Insert picture description here

MVVM It's quite mature , Mainly used but not only in network application development . Now popular MVVM Framework has Vue.js,Anfular JS

1.2 Why use MVVM

MVVM Patterns and MVC Model as , The main purpose is to separate views (View) And models (Model), There are several benefits

  • Low coupling : View (View) Can be independent of Model Changes and modifications , One ViewModel Can be bound to different View On , When View When it changes Model It can be the same , When Model When it changes View It can be the same .
  • Reusable : You can put some view logic in a ViewModel Inside , Let a lot of View Reuse this view logic .
  • Independent development : Developers can focus on the development of business logic and data (ViewMode), Designers can focus on page design .
  • Testable : Interfaces are always difficult to test , And now the test can target ViewModel To write .

MVVM Part of the
 Insert picture description here

(1)View

View Is the view layer , That's the user interface . The front end is mainly composed of HTH L and csS To build , To make it easier to show vi eu to del perhaps Hodel Layer data , Various front-end and back-end template languages have emerged , such as FreeMarker,Thyme leaf wait , The major MV VM The frame is like Vue.js.Angular JS, EJS They also have their own built-in template languages for building user interfaces .

(2)Model

Model Data model , It generally refers to various business logic processing and data manipulation carried out by the back end , Mainly around the database system . The difficulty here mainly lies in the need for unified interface rules with the front end

(3)ViewModel

ViewModel It is the view data layer generated and maintained by the front-end developers . In this layer , Front end developers get from the back end Model Data conversion processing , Make secondary packaging , To generate compliance View Layer uses the expected view data model .

It should be noted that View Model The encapsulated data model includes two parts: view state and view behavior , and Model Layer's data model is state only

  • For example, what is displayed in this section of the page , What is shown in that block belongs to the view state ( Exhibition )
  • What happens when the page loads in , What happens when you click on this piece , What happens when this piece is scrolling is a view behavior ( Interaction )

View state and behavior are encapsulated in View Model in . Such packaging enables View Model It can be described completely View layer . Thanks to bidirectional binding , View Model The content of will be displayed in real time View layer , It's exciting , Because front-end developers no longer have to manipulate inefficiently and troublesome DOM To update the view .

MVVM The frame has made the dirtiest and most tired piece , We developers only need to deal with and maintain View Model, Update the data view and it will be updated automatically , Real event driven programming .

View Layers don't show Model Layer data , It is ViewModel The data of , from ViewModel Responsible for working with Model Layer interaction , This is Completely decoupled View Layer and the Model layer , This decoupling is critical , It is an important part of the implementation of the front and rear end separation scheme

1.3 Vue

Vue( pronunciation /vju/, Be similar to view) Is a progressive framework for building user interfaces , Published on 2014 year 2 month . Unlike other large frameworks , Vue Designed to be applied layer by layer from the bottom up .Vue The core library focuses only on the view layer , Not only easy to get started , It's also easy to work with third-party libraries ( Such as :vue-router,vue-resource,vue x) Or integration of existing projects

(1)MVVM Pattern implementer

  • Model: The model layer , Here it means JavaScript object
  • View: View layer , Here it means DOM(HTML Element of operation )
  • ViewModel: Middleware connecting views and data , Vue.js Namely MVVM Medium View Model Layer implementers

stay MVVM Architecture , Data and views are not allowed to communicate directly , Only through ViewModel To communication , and View Model Is to define a Observer The observer

  • ViewModel Be able to observe changes in data , And update the content of the view
  • ViewModel Be able to monitor changes in the view , And be able to notify data changes

thus , We can get a general idea of , Vue.js It's just one. MV VM Implementer , His core is to achieve DOM Listening and data binding
(2) Why use Vue.js

  • Lightweight , Small size is an important indicator .Vue.js After compression, there are only 20 many kb(Angular After the compression 56kb+,React After the compression 44kb+)
  • Mobile first . More suitable for mobile terminals , For example, mobile terminal Touch event
  • Easy to use , The learning curve is smooth , The documentation is complete
  • Absorbed Angular( modularization ) and React( fictitious DOM) Strengths , And has its own unique function , Such as : Compute properties
  • Open source , High community activity

1.4 first Vue Program (Hello World)

development environment :IDEA( because IDEA Can install Vue Plug in for )

Vue.js: We usually use cdn Import

<script src=“https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js”></script>
<!-- or -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
123
  • Create an empty project , Create a folder ,new One HTML file
  • Write code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>

<!--view layer , Templates -->
<div id="app">
<!--  Data binding -->
    {
   {message}}
</div>

<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> //  Create a Vue example  var vm = new Vue({
       el:"#app", /*Model: data */ data:{
       message:"hello,vue -----cvzhanshi!" } }); </script>
</body>
</html>
12345678910111213141516171819202122232425262728

explain

  • el:“#app” -----> Bound element ID
  • data:{message:“hello,vue —cvzhanshi!”} ----> One of the data objects is called message Properties of , And set the initial value hello,vue —cvzhanshi
  • { {message}} -----> Realize data binding function

Running effect
 Insert picture description here

test

For a more intuitive experience Vue Bring data binding capabilities , We need to test it in the browser , The operation process is as follows :
??1、 Run the first one on the browser Vue Applications , Enter developer tools
??2、 Input at the console vm.message=‘HelloWorld’, And then go back , You will find that the content displayed in the browser will directly become HelloWorld, No page refresh required
?? At this point, you can directly input vm.message To modify the value , The middle can be omitted data Of , In this operation , I didn't take the initiative to operate DOM, Let the content of the page change , That's what it's all about Vue Implementation of data binding function based on ; MV VM The pattern requires View Model Layer is to use observer mode to monitor and bind data , In order to achieve the rapid response of data and view

understand View Model: It can be likened to an observer , Changes in data have been monitored , Immediately update the value bound to the page , No need to update the page , No action required DOM object , Equivalent to a virtual DOM object

② Vue Basic grammar

2.1 v-bind

Test code

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>

<div id="app">
  <span v-bind:title="message">
     Hover for a few seconds to see the prompt information of dynamic binding here !
  </span>

    <!--1. Import Vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script type="text/javascript"> //  Create a Vue example  var vm = new Vue({
       el:"#app", /*Model: data */ data:{
       message:"hello,vue -----cvzhanshi!" } }); </script>
</div>
</body>
</html>
12345678910111213141516171819202122232425262728

 Insert picture description here

explain **:

  • What you see v-bind attribute go by the name of Instructions . Instructions are prefixed with v-, To show that they are Vue Special offers attribute
  • They're going to be rendering DOM Apply special responsive behavior on

ad locum , The directive means :“ This element node's title attribute and Vue Example of message property bring into correspondence with ”

If you open the browser again JavaScript Console , Input app.message = ' New news ', You'll see the binding again title attribute Of HTML It has been updated

2.2 v-if、v-else

Test code 1

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="app">
    <h1 v-if="type">Yes</h1>
    <h1 v-else>No</h1>

</div>

<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var vm = new Vue({
       el:"#app", /*Model: data */ data:{
       type: true } }); </script>
</body>
</html>
123456789101112131415161718192021222324252627

 Insert picture description here

test

1. Run... On a browser , Open console
2. Input at the console vm.type=false And then go back , You will find that the content displayed in the browser will directly become NO
?? notes : Use v-* Property binding data is not required Double flower brackets Wrapped
 Insert picture description here

Test code 2

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="app">
    <h1 v-if="type==='A'">A</h1>
    <h1 v-else-if="type==='B'">B</h1>
    <h1 v-else-if="type==='D'">D</h1>
    <h1 v-else>C</h1>

</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var vm = new Vue({
       el:"#app", /*Model: data */ data:{
       type: 'A' } }); </script>
</body>
</html>
12345678910111213141516171819202122232425262728

test

1. Run... On a browser , Open console
2. Input at the console vm.type="D" And then go back , You will find that the content displayed in the browser will directly become D
 Insert picture description here

notes :=== Three equal signs in JS Is absolutely equal to ( That is, data and type should be equal )

2.3 v-for

Test code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="app">
    <li v-for="(item,index) in items">
        {
   {item.message}}---{
   {index}}
    </li>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var vm = new Vue({
       el:"#app", /*Model: data */ data:{
       items:[ {
      message:'cvzhanshi'}, {
      message:'ursula'}, {
      message:'cvzhanshi-ursula'} ] } }); </script>
</body>
</html>
123456789101112131415161718192021222324252627282930

Format specification

<div id="app">
    <li v-for="(item,index) in items">
        {
   {item.message}}---{
   {index}}
    </li>
</div>
12345

notes :items It's an array ,item Is an alias for an array element iteration ,index Is the sequence number of the iteration

test

  • Open console , Input at the console vm.items.push({message:'vue hello'}), Try appending a piece of data , You will find that the page has also added data
     Insert picture description here

2.4 v-on

1、 It can be used v-on Command monitoring DOM event , And run some on trigger JavaScript Code

Sample code 1

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="example-1">
    <button v-on:click="counter += 1">Add 1</button>
    <p>The button above has been clicked {
   { counter }} times.</p>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example1 = new Vue({
       el: '#example-1', data: {
       counter: 0 } }); </script>
</body>
1234567891011121314151617181920212223

? Click the button attribute value + 1
 Insert picture description here

2、 However, many of the event processing logic will be more complex , So directly JavaScript The code is written in v-on It is not feasible in the instruction . therefore v-on You can also receive a method name that needs to be called

Test code 2

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="example-2">
    <!-- `greet`  Is the method name defined below  -->
    <button v-on:click="greet">Greet</button>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       name: 'Vue.js' }, //  stay  `methods`  Object  methods: {
       greet: function (event) {
       // `this`  Point to the current... In the method  Vue  example  alert('Hello ' + this.name + '!') // `event`  It's original  DOM  event  if (event) {
       alert(event.target.tagName) } } } }) ; </script>
</body>
</html>
123456789101112131415161718192021222324252627282930313233343536

 Insert picture description here

③ Vue Form double binding & Components

3.1 Two way binding of form data

Data bidirectional binding , That is, when the data changes , The view changes , When the view changes , The data will also change synchronously .

Be careful : What we call data bidirectional binding , It must be for UI Control UI Control does not involve data bidirectional binding .

You can use it. v-model Instruction in form 、 And elements . It automatically selects the correct method to update the element based on the control type .v-model Responsible for monitoring user input events to update data , In addition, some special treatment is carried out for some extreme scenes .

Be careful :v-model All form elements will be ignored value、checked、selected The initial value of the property and always Vue Instance data as data source . You should go through JavaScript In the component's data Initial value declared in option

v-model Use different... Internally for different input elements property And throw out different events :

  • text and textarea Element usage value property and input event ;
  • checkbox and radio Use checked property and change event ;
  • select Fields will value As prop And will change As an event .

Single line text

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="example-2">
    <input v-model="message" placeholder="edit me">
    <p>Message is: {
   { message }}</p>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       message: '' } }); </script>
</body>
</html>
123456789101112131415161718192021222324

 Insert picture description here

Multiline text

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>cVzhanshi</title>
</head>
<body>
<!--view layer , Templates -->
<div id="example-2">
    <span>Multiline message is:</span>
    <p style="white-space: pre-line;">{
   { message }}</p>
    <br>
    <textarea v-model="message" placeholder="add multiple lines"></textarea>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       message: '' } }); </script>
</body>
</html>
1234567891011121314151617181920212223242526

 Insert picture description here

Be careful : Interpolation in text area ({ {text}}) It doesn't work , application v-model Instead of

Check box

  • A single check box is bound to a Boolean value
<!--view layer , Templates -->
<div id="example-2">
    <input type="checkbox" id="checkbox" v-model="checked">
    <label for="checkbox">{
   { checked }}</label>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       checked: 'true' } }); </script>
123456789101112131415
  • Multiple check boxes , Bind to the same array
<!--view layer , Templates -->
<div id="example-2">
    <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
    <label for="jack">Jack</label>
    <input type="checkbox" id="john" value="John" v-model="checkedNames">
    <label for="john">John</label>
    <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
    <label for="mike">Mike</label>
    <br>
    <span>Checked names: {
   { checkedNames }}</span>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       checkedNames: [] } }); </script>
123456789101112131415161718192021

 Insert picture description here

Radio button

<!--view layer , Templates -->
<div id="example-2">
    <input type="radio" id="one" value="One" v-model="picked">
    <label for="one">One</label>
    <br>
    <input type="radio" id="two" value="Two" v-model="picked">
    <label for="two">Two</label>
    <br>
    <span>Picked: {
   { picked }}</span>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       picked: '' } }); </script>
1234567891011121314151617181920

 Insert picture description here

Selection box

<!--view layer , Templates -->
<div id="example-2">
    <select v-model="selected">
        <option disabled value=""> Please select </option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
    <span>Selected: {
   { selected }}</span>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> var example2 = new Vue({
       el: '#example-2', data: {
       selected: '' } }); </script>
1234567891011121314151617181920

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-GPLrSof7-1624434583005)(Vue.assets/1624434357994.png)]

If v-model The initial value of the expression failed to match any options ,`` The element will be rendered as “ Not selected ” state . stay iOS in , This prevents the user from choosing the first option . Because in this case ,iOS Not trigger change event . therefore , It is more recommended to provide a disable option with a null value like above .

3.2 Components

Components are reusable Vue example , To put it bluntly, it's a set of reusable templates , Follow JSTL Custom labels for 、Thymeleal Of th:fragment The same is true of equal frames , Usually an application is organized as a nested component tree

 Insert picture description here
for example , You may have a header 、 Sidebar 、 Content area and other components , Each component also contains other links like navigation 、 Components like blogs

  • Customize the first component
<!--view layer , Templates -->
<div id="app">
    <cvzhanshi></cvzhanshi>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> Vue.component("cvzhanshi",{
       template: '<li>Hello cVzhanshi</li>' }); var vm = new Vue({
       el: '#app', data: {
       selected: '' } }); </script>
1234567891011121314151617

 Insert picture description here

explain :

  • Vue.component(): Certified components
  • cvzhanshi: Name of custom component
  • template: Templates for components
  • Use props Property passing parameters

<!--view layer , Templates -->
<div id="app">
    <cvzhanshi v-for="item in items" v-bind:course="item"></cvzhanshi>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> Vue.component("cvzhanshi",{
       props: ['course'], template: '<li>{
      {course}}</li>' }); var vm = new Vue({
       el: '#app', data:{
       items:["java","Linux"," front end "] } });![ Insert picture description here ](https://img-blog.csdnimg.cn/20200616222020393.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Bhbl9oMTk5NQ==,size_16,color_FFFFFF,t_70#pic_center) </script>
12345678910111213141516171819

explain :

  • v-for=“item in items”: Traverse Vue The name defined in the instance is items Array of , And create the same number of components
  • v-bind:course=“item”: The item Item is bound to the component props Definition is named course Attribute ;= The one on the left of number one course by props The name of the property defined , On the right is item in items Traversal in item Item value

④ Axios asynchronous communication

4.1 Axios brief introduction

Axios Is an open source, can be used in the browser side and Node JS Asynchronous communication framework of , Her main role is to achieve AJAX asynchronous communication , Its functional features are as follows :

  • Created from the browser XMLHttpRequests
  • from node.js establish http request
  • Support Promise API[JS Middle chain programming ]
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatic conversion JSON data
  • The client supports defense XSRF( Cross-site request forgery )

because Vue.js It's a view level framework and the author ( Especially the rain creek ) Strictly abide by SoC( The separation principle of attention ) therefore Vue.js Does not contain AJAX Communication function , To solve the communication problem , The author has developed a separate program called vue-resource Plug in for , But entering 2.0 After the release, the maintenance of the plug-in was stopped and recommended Axios frame .

because jQuery operation Dom Too often , So use less

4.2 test Axios

  • Prepare pseudo data first
{
    
  "name": "cv warrior ",
  "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
  "page": 1,
  "isNonProfit": true,
  "address": {
    
    "street": " Han guangmen ",
    "city": " Xi'an, Shaanxi ",
    "country": " China "
  },
  "links": [
    {
    
      "name": "bilibili",
      "url": "https://bilibili.com"
    },
    {
    
      "name": "cv warrior ",
      "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
    },
    {
    
      "name": " Baidu ",
      "url": "https://www.baidu.com/"
    }
  ]
}
12345678910111213141516171819202122232425
  • Test code
<!DOCTYPE html>
<html lang="en" xmlns:v-binf="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--v-cloak  Solve the flicker problem -->
    <style> [v-cloak]{
       display: none; } </style>
</head>
<body>
<div id="vue" v-cloak>
    <div> Place names :{
   {info.name}}</div>
    <div> Address :{
   {info.address.country}}--{
   {info.address.city}}--{
   {info.address.street}}</div>
    <div> link :<a v-bind:href="info.url">{
   {info.url}}</a> </div>
</div>

<!-- introduce js file -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript"> var vm = new Vue({
       el:"#vue", //data: attribute :vm data(){
       return{
       info:{
       name:null, address:{
       country:null, city:null, street:null }, url:null } } }, mounted(){
      // Hook function  axios .get('../data.json') .then(response=>(this.info=response.data)); } }); </script>
</body>
</html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

explain :

  1. It's used here v-bind take a:href The property value of is the same as the Vue The data in the instance is bound
  2. Use axios Framework of the get Method request AJAX And automatically encapsulate the data into Vue In the data object of the instance
  3. We are data The data structure in must be the same as Ajax The data format returned from the response matches

Vue Life cycle diagram
 Insert picture description here

⑤ Vue Compute properties 、 content distribution 、 Custom events

5.1 Compute properties

The focus of computing attributes is attribute Two words up ( Attributes are nouns ), First of all, it's a attribute Secondly, this attribute has Calculation The ability of ( Calculation is a verb ), there Calculation It's just a function : To put it simply , It is a property that can cache the result of calculation ( Turning behavior into static attributes ), That's it ; Think of it as caching

Test code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <!--view layer , Templates -->
        <div id="app">
            <p>currentTime1:{
   {currentTime1()}}</p>
            <p>currentTime2:{
   {currentTime2}}</p>
        </div>
        <!--1. Import Vue.js-->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
        <script type="text/javascript"> var vm = new Vue({
       el:"#app", data:{
       message:"cvzhanshi" }, methods:{
       currentTime1:function(){
       return Date.now();// Return a timestamp  } }, computed:{
       currentTime2:function(){
      // Compute properties :methods,computed Method names cannot be duplicate , After the double name , It will only call methods Methods  this.message; return Date.now();// Return a timestamp  } } }); </script>
    </body>
</html>
1234567891011121314151617181920212223242526272829303132333435

Be careful :methods and computed You can't have the same name for things in the library , After the double name , It will only call methods Methods

explain :

  • methods: Define methods , Call methods using currentTime1(), Need to be in parentheses
  • computed: Define calculation properties , Call properties using currentTime2, Brackets are not required :this.message To be able to currentTime2 Observe data change and change
  • How the value in the method changes , Then the cache will refresh ! Can be used on the console vm.message=”cvzhanshi", Change the value of the data , Test again and observe the effect !

summary

When calling a method , We need to do calculation every time , Since there is a calculation process, there must be system overhead , Well, if the result doesn't change very often ? At this point, you can consider caching the result , It's easy to do this with computational properties , The main feature of computing attributes is to cache the computing results that don't change frequently , To save our system overhead ;

5.2 content distribution ( slot )

stay Vue.js We use `` Element as the exit to host the distribution , It can be called a slot , It can be applied in the scene of combining components

demand : You need to put the following , Let the title and content insert content through the slot

<p> title </p>
<ul>
    <li>abcd</li>
    <li>abcd</li>
    <li>abcd</li>
</ul>
123456
  • Define an agent component
 Vue.component('todo',{
    
        template:'<div>\ <div> Agency matters </div>\ <ul>\ <li>cvzhanshi study Java</li>\ </ul>\ </div>'
    });
12345678
  • Leave a slot in the code above , namely slot
 Vue.component('todo',{
    
        template:'<div>\ <slot"></slot>\ <ul>\ <slot"></slot>\ </ul>\ </div>'
    });
12345678
  • Define a name todo-title To do Title component of and todo-items To do content component of
Vue.component('todo-title',{
        props:['title'],
        template:'<div>{
   {title}}</div>'
    });
   
// there index, Is the subscript of the array , Use for Loop traversal , It can be recycled !
    Vue.component("todo-items",{
        props:["item","index"],
        template:"<li>{
   {index+1}},{
   {item}}</li>"
    });

1234567891011
  • slot adopt name Binding with components
 Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });

123456789
  • Instantiation Vue And initialize the data
 var vm = new Vue({
        el:"#vue",
        data:{
            todoItems:['test1','test2','test3']
        }
    });
123456
  • Insert the data into the reserved position through the slot
<todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item" ></todo-items>
    </todo>
1234

explain :

? slot: It is used for binding components

? :title --> yes v-bind:title Abbreviation

  • Complete code
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <!--view layer , Templates -->
        <div id="vue">
            <todo>
                <todo-title slot="todo-title" v-bind:title="title"></todo-title>
                <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
                <!-- The following is the abbreviation -->
                <todo-items slot="todo-items" v-for="item in todoItems" :item="item" ></todo-items>
            </todo>
        </div>
        <!--1. Import Vue.js-->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
        <script type="text/javascript"> Vue.component('todo',{
       template:'<div>\ <slot name="todo-title"></slot>\ <ul>\ <slot name="todo-items"></slot>\ </ul>\ </div>' }); Vue.component('todo-title',{
       props:['title'], template:'<div>{
      {title}}</div>' }); // there index, Is the subscript of the array , Use for Loop traversal , It can be recycled ! Vue.component("todo-items",{
       props:["item"], template:"<li>{
      {item}}</li>" }); var vm = new Vue({
       el:"#vue", data:{
       title:"cvzhanshi study java", todoItems:['test1','test2','test3'] } }); </script>
    </body>
</html>

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

 Insert picture description here

5.3 Custom events

We can find a problem through the appeal code , If the deletion operation is to be completed in the component , So how to delete components Vue Data in the example ?

example :[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6cl2ga6d-1624517862625)(Vue.assets/1624501228359.png)]

The delete button is in the component , Click the delete button to delete the corresponding data .

read Vue Tutorial , This involves parameter passing and event distribution , Vue It provides us with the function of custom event, which helps us solve this problem ; Used in components this.$emit(‘ Custom event name ’, Parameters ) , In the view layer, it is bound by custom events Vue Method of deleting operation in

step :

  • stay Vue Define a delete method in the instance removeItems()
methods: {
    
		removeItems: function (index) {
    
		this.todoItems.splice(index,1);
	}
}
12345

explain splice(index,n) The method is to operate index The subscript begins n Elements

  • Customize events and bind them in the view layer Vue The method in the example
<div id="vue">
    <todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems" :item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>
</div>
1234567

The custom event is remove, adopt v-on binding removeItems Method

  • Bind custom events in the corresponding components
Vue.component("todo-items",{
    
    props:["item","index"],
    template:"<li>{
    {item}}---{
    {index}}<button @click='remove'> Delete </button></li>",
    methods: {
    
        remove: function (index) {
    
            this.$emit('remove',index);
        }
    }
});
123456789

The complete code is as follows

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view layer , Templates -->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems" :item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>
</div>
<!--1. Import Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript"> Vue.component('todo',{
       template:'<div>\ <slot name="todo-title"></slot>\ <ul>\ <slot name="todo-items"></slot>\ </ul>\ </div>' }); Vue.component('todo-title',{
       props:['title'], template:'<div>{
      {title}}</div>' }); // there index, Is the subscript of the array , Use for Loop traversal , It can be recycled ! Vue.component("todo-items",{
       props:["item","index"], template:"<li>{
      {item}}---{
      {index}}<button @click='remove'> Delete </button></li>", methods: {
       remove: function (index) {
       this.$emit('remove',index); } } }); var vm = new Vue({
       el:"#vue", data:{
       title:"cvzhanshi study java", todoItems:['test1','test2','test3'] }, methods: {
       removeItems: function (index) {
       this.todoItems.splice(index,1); } } }); </script>
</body>
</html>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455

Logical understanding
 Insert picture description here

5.4 Vue Introduction summary

The core : Data driven , Componentization

advantage : Learn from it AngularJS Modular development and React The virtual Dom, fictitious Dom Is to put Demo Operations are put into memory for execution ;

Common properties :

  • v-if
  • v-else-if
  • v-else
  • v-for
  • v-on The binding event , Abbreviation @
  • v-model Data bidirectional binding
  • v-bind Bind parameters to components , Abbreviation :

Componentization :

  • Combined components slot slot
  • Component internal binding events need to use this.$emit(“ Event name ”, Parameters );
  • Characteristics of computational properties , Cache computing data

follow SoC The separation principle of attention ,Vue It's a pure view frame , Does not contain , such as Ajax And so on , To solve the communication problem , We need to use Axios The framework does asynchronous communication ;

⑥ first Vue-cli project

6.1 Vue-cli brief introduction

vue-cli An official scaffold , Used to quickly generate a vue Project template

Predefined directory structure and basic code , It's like we're creating Maven Project, you can choose to create a skeleton project , The estimated project is scaffolding , Our development is faster

The function of the project

  • Unified directory structure
  • Local debugging
  • Thermal deployment
  • unit testing
  • Integrated packaging Online

6.2 Environment configuration

  • Node.js

Download address : http://nodejs.cn/download/ When installing, continue to the next step until the end

Confirm whether the installation is successful :

  • stay cmd Run in node -v command , Check whether the version number can be output
  • stay cmd Run in npm -v command , Check whether the version number can be output

 Insert picture description here

  • install node.js Taobao image Accelerator (cnpm)
# -g  It's a global installation 
npm install cnpm -g

#  Or use the following statement to solve npm The problem of slow speed , But every time install Need to be ( Ma fa )
npm install --registry=https://registry.npm.taobao.org
12345
  • install vue-cli
cnpm instal1 vue-cli-g
# Test for successful installation # See which templates you can create vue Applications , Usually we choose webpack
vue list
123

 Insert picture description here

6.3 first vue-cli Applications

  • Find a project path ( Empty folder )
  • Create one based on webpack Template vue Applications
#1、 First, you need to go to the corresponding directory  cd E:\study\Java\workspace\workspace_vue
#2、 there myvue Is the name of the top day , You can name it according to your own needs 
vue init webpack myvue
123
  • Actions required for the creation process

    All the way no
     Insert picture description here

Project name: Project name , By default, you can return
Project description: Project description , By default, you can return
Author: Project the author , By default, you can return
Install vue-router: Whether to install vue-router, choice n Not to install ( Later, you need to add it manually )
Use ESLint to lint your code: Whether to use ESLint Do code checking , choice n Not to install ( Later, you need to add it manually )
Set up unit tests: Unit test related , choice n Not to install ( Later, you need to add it manually )
Setupe2etests with Nightwatch: Unit test related , choice n Not to install ( Later, you need to add it manually )
Should we run npm install for you after the,project has been created: Initialize directly after creation , choice n, Let's do it manually ; Running results

When something goes wrong , It will give a prompt. We just follow the prompt
 Insert picture description here

  • Initialize and run
cd myvue
npm install
npm run dev
123

 Insert picture description here

visit localhost:8080 that will do

 Insert picture description here

⑦ webpack Use

7.1 install Webpack

WebPack Is a module loader and packaging tool , It can bring all kinds of resources together , Such as JS、JSX、ES 6、SASS、LESS、 Pictures and so on are processed and used as modules

install

npm install webpack -g
npm install webpack-cli -g
12

Test installation successful :

webpack -v
webpack-cli -v
12

 Insert picture description here

To configure

  • entry: Entrance file , Appoint Web Pack Which file to use as the entry to the project
  • output: Output , Appoint WebPack Put the processed file to the specified path
  • module: modular , Used to handle all kinds of files
  • plugins: plug-in unit , Such as : Hot update 、 Code reuse, etc
  • resolve: Set the path to
  • watch: monitor , It is used to directly package the changed files
module.exports = {
    
	entry:"",
	output:{
    
		path:"",
		filename:""
	},
	module:{
    
		loaders:[
			{
    test:/\.js$/,;\loade:""}
		]
	},
	plugins:{
    },
	resolve:{
    },
	watch:true
}
123456789101112131415

Direct operation webpack Command packaging

7.2 Use webpack

  • Create project

stay workspace Create folder in webpack-study, And then use IDEA open

  • Create a file called modules The catalog of , For placement JS Modules and other resource files
  • stay modules Create module file under hello.js
// Expose a way :sayHi
exports.sayHi = function(){
    
    document.write("<div>Hello Webpack</div>");
}
1234
  • stay modules Next create a new one called main.js Entry file main.js, Used to set... When packing entry attribute
//require  Import a module , You can call the methods in this module 
var hello = require("./hello");
hello.sayHi();
123
  • Create in project directory webpack.config.js The configuration file , Use webpack Command packaging
module.exports = {
    
    entry:"./modules/main.js",
    output:{
    
        filename:"./js/bundle.js"
    }
}
123456

pack :

explain : If packaging fails , Run with administrator privileges webpack

 Insert picture description here

  • Create in project directory HTML page , Such as index.html, Import webpack After packaging JS file
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title> Madness theory Java</title>
    </head>
    <body>
        <script src="dist/js/bundle.js"></script>
    </body>
</html>
12345678910
  • Open it directly index.html
     Insert picture description here

notes

#  Parameters --watch  For monitoring changes , If there's a change in what you're packing , Just repackage it 
webpack --watch
12

⑧ Vue vue-router route

8.1 install

  • Based on the first vue-cli Test learning ; To look at first node modules Whether there is vue-router, vue-router It's a plug-in package , So we still need to use n pm/cn pm To install
npm install vue-router --save-dev
1

 Insert picture description here

  • If you use it in a modular project , Must pass Vue.use() Explicitly install the routing function
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);
1234

8.2 Test route

  • Delete the first vue-cli Useless things in the project
  • components Store our own components in the directory
  • Define several of your own components Content.vue 、Main.vue、cVzhanshi.vue

Content.vue

<template>
	<div>
		<h1> Content page </h1>
	</div>
</template>

<script>
	export default {
		name:"Content"
	}
</script>
1234567891011

Main.vue

<template>
<div>
    <h1> home page </h1>
    </div>
</template>

<script>
    export default {
        name:"Main"
    }
</script>
1234567891011

cVzhanshi.vue

<template>
<div>
    <h1>cVzhanshi</h1>
</div>
</template>

<script>
    export default {
        name:"cVzhanshi"
    }
</script>
1234567891011
  • Installation routing , stay src Under the table of contents , Create a new folder :router, Dedicated storage route , Configure the routing index.js
import Vue from'vue'
// Import routing plug-in 
import Router from 'vue-router'
// Import the components defined above 
import Content from '../components/Content'
import Main from '../components/Main'
import cVzhanshi from "../components/cVzhanshi";
// Installation routing 
Vue.use(Router) ;
// Configure the routing 
export default new Router({
    
  routes:[
    {
    
      // Routing path 
      path:'/content',
      // Routing name 
      name:'content',
      // Jump to component 
      component:Content
    },{
    
      // Routing path 
      path:'/main',
      // Routing name 
      name:'main',
      // Jump to component 
      component:Main
    }
    ,{
    
      // Routing path 
      path:'/cvzhanshi',
      // Routing name 
      name:'main',
      // Jump to component 
      component:cVzhanshi
    }
  ]
});
12345678910111213141516171819202122232425262728293031323334353637
  • stay main.js Configure routing in
import Vue from 'vue'
import App from './App'

import router from './router'// Automatically scan the routing configuration inside 
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    
  el: '#app',
  router,
  components: {
     App },
  template: '<App/>'
})
12345678910111213
  • stay App.vue Use routing in
<template>
  <div id="app">
    <!--
          router-link: By default, it will be rendered as a <a> label ,to Property for the specified link 
          router-view: Used to render components that route matches to 
        -->
    <h1>cVzhanshi</h1>
    <router-link to="/main"> home page </router-link>
    <router-link to="/content"> Content </router-link>
    <router-link to="/cvzhanshi">cVzhanshi</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>
12345678910111213141516171819
  • function npm run dev, Then the browser accesses localhost:8080
     Insert picture description here

⑨ Actual combat small demo

9.1 Create a project

  • Create a file called hello-vue The engineering of
vue init webpack hello-vue
1
  • Installation dependency , vue-router、element-ui、sass-loader and node-sass Four plug-ins
# Enter the project directory 
cd hello-vue
# install vue-routern 
npm install vue-router --save-dev
# install element-ui
npm i element-ui -S
# Installation dependency 
npm install
#  install SASS loader 
cnpm install sass-loader node-sass --save-dev
# Start test 
npm run dev
123456789101112
  • npm Command specification
  • npm install moduleName: Install the module to the project directory

  • npm install -g moduleName:-g It means to install the module to the global , The specific location of the disk depends on npm

    config prefix The location of

  • npm install -save moduleName:–save Install the module into the project directory , And in package Of documents dependencies Node write dependency ,-S Is the abbreviation of the command

  • npm install -save-dev moduleName:–save-dev Install the module into the project directory , And in package Of documents devDependencies Node write dependency ,-D Is the abbreviation of the command

  • idea Open the created project

9.2 Create a landing page

  • First delete the useless files
  • The project structure is as follows
     Insert picture description here

explain :

  • assets: For storing resource files
  • components: To hold Vue Functional components
  • views: To hold Vue View component
  • router: To hold vue-router To configure
  • stay views Create a home page view under the directory Main.vue Components
<template>
<div> home page </div>
</template>
<script>
    export default {
        name:"Main"
    }
</script>
<style scoped>
</style>
12345678910
  • stay views Create a login page view under the directory Login.vue Components
<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title"> Welcome to login </h3>
      <el-form-item label=" account number " prop="username">
        <el-input type="text" placeholder=" Please enter your account number " v-model="form.username"/>
      </el-form-item>
      <el-form-item label=" password " prop="password">
        <el-input type="password" placeholder=" Please input a password " v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')"> Sign in </el-button>
      </el-form-item>
    </el-form>

    <el-dialog title=" reminder " :visible.sync="dialogVisiable" width="30%" :before-close="handleClose">
      <span> Please enter your account number and password </span>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false"> determine </el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "Login",
      data(){
          return{
            form:{
              username:'',
              password:''
            },
            // Form validation , Need to be in  el-form-item  Add... To the element prop attribute 
            rules:{
              username:[
                {required:true,message:" Account number cannot be empty ",trigger:"blur"}
              ],
              password:[
                {required:true,message:" The password cannot be empty ",tigger:"blur"}
              ]
            },

            // Dialog shows and hides 
            dialogVisible:false
          }
      },
      methods:{
          onSubmit(formName){
            // Bind validation to the form 
            this.$refs[formName].validate((valid)=>{
              if(valid){
                // Use vue-router Route to the specified interface , This is called programmed navigation 
                this.$router.push('/main');
              }else{
                this.dialogVisible=true;
                return false;
              }
            });
          }
      }
    }
</script>

<style lang="scss" scoped>
  .login-box{
    border:1px solid #DCDFE6;
    width: 350px;
    margin:180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }
  .login-title{
    text-align:center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
</style>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  • stay router Create a directory called index.js Of vue-router Routing configuration file
// Import vue
import Vue from 'vue';
import VueRouter from 'vue-router';
// Import components 
import Main from "../views/Main";
import Login from "../views/Login";
// Use 
Vue.use(VueRouter);
// export 
export default new VueRouter({
    
  routes: [
    {
    
      // The login page 
      path: '/main',
      component: Main
    },
    // home page 
    {
    
      path: '/login',
      component: Login
    },
  ]

})
123456789101112131415161718192021222324
  • To write APP.vue
<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>


    export default {
        name: 'App',

    }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>
12345678910111213141516171819202122232425
  • stay main.js Configure routing in
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'

Vue.config.productionTip = false

Vue.use(router)
Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
    
  el: '#app',
  router,
  render:h=>h(App)
})
123456789101112131415161718
  • test npm run dev

explain : If something goes wrong : Probably because sass-loader Compile error due to too high version of , You can go to package.json File the sass-loder The version of , It could be node-sass Version too high , Read the wrong content and modify the corresponding version

9.3 Route nesting

Nested routes are also called sub routes , in application , It is usually composed of multiple nested components

  • Create a user information component , stay views/user Create a directory called Profile.vue View component of
<template>
  <h1> Personal information </h1>
</template>
<script>
  export default {
    name: "UserProfile"
  }
</script>
<style scoped>
</style>
12345678910
  • In the user list component views/user Create a directory called List.vue View component of
<template>
  <h1> User list </h1>
</template>
<script>
  export default {
    name: "UserList"
  }
</script>
<style scoped>
</style>
12345678910
  • Modify the home page view , We modify Main.vue View component , Here we use ElementUI Layout container components
<template>
    <div>
      <el-container>
        <el-aside width="200px">
          <el-menu :default-openeds="['1']">
            <el-submenu index="1">
              <template slot="title"><i class="el-icon-caret-right"></i> User management </template>
              <el-menu-item-group>
                <el-menu-item index="1-1">
                <!-- Where to insert -->
                  <router-link to="/user/profile"> Personal information </router-link>
                </el-menu-item>
                <el-menu-item index="1-2">
                <!-- Where to insert -->
                  <router-link to="/user/list"> User list </router-link>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title"><i class="el-icon-caret-right"></i> Content management </template>
              <el-menu-item-group>
                <el-menu-item index="2-1"> Classification management </el-menu-item>
                <el-menu-item index="2-2"> The content list </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-aside>

        <el-container>
          <el-header style="text-align: right; font-size: 12px">
            <el-dropdown>
              <i class="el-icon-setting" style="margin-right: 15px"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item> Personal information </el-dropdown-item>
                <el-dropdown-item> Log out </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-header>
          <el-main>
          <!-- Show the view here -->
            <router-view />
          </el-main>
        </el-container>
      </el-container>
    </div>
</template>
<script>
    export default {
        name: "Main"
    }
</script>
<style scoped lang="scss">
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }
  .el-aside {
    color: #333;
  }
</style>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  • Added components , Go to router Modify the configuration file
// Import vue
import Vue from 'vue';
import VueRouter from 'vue-router';
// Import components 
import Main from "../views/Main";
import Login from "../views/Login";
// Import sub modules 
import UserList from "../views/user/List";
import UserProfile from "../views/user/Profile";

// Use 
Vue.use(VueRouter);
// export 
export default new VueRouter({
    
  routes: [
    {
    
      // The login page 
      path: '/main',
      component: Main,
      //  Write sub module 
      children: [
        {
    
          path: '/user/profile',
          component: UserProfile,
        }, {
    
          path: '/user/list',
          component: UserList,
        },
      ]
    },
    // home page 
    {
    
      path: '/login',
      component: Login

    },
  ]
})

123456789101112131415161718192021222324252627282930313233343536373839
  • Run the test
     Insert picture description here

9.4 Parameter passing and redirection

9.4.1 Parameter passing

Method 1

  • Modify routing configuration , Mainly router Under the index.js Medium path Attribute added :id Such placeholders
{
    
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile
}

123456
  • View layer transfer parameters
<!--name Is the name of the component  params It's the parameter of the transmission   If you want to pass parameters, you need to use v:bind: To bind -->
<router-link :to="{name:'UserProfile',params:{id:1}}"> Personal information </router-link>

123

explain : At this point we are Main.vue Medium route-link Location to Change it to :to, To use this property as an object , Be careful router-link Medium name The attribute name Be sure to and In the routing name The attribute name matching , Because of this Vue To find the corresponding routing path

  • Receiving parameters
<template>
  <!--   All elements must be under the root node -->
  <div>
    <h1> Personal information </h1>
    {
   {$route.params.id}}
  </div>
</template>

12345678

explain : All elements must be under the root node , Otherwise, an error will be reported

  • test
     Insert picture description here

Method 2 Use props Reduce coupling

  • Modify routing configuration , Mainly in the router Under the index.js Added... To the routing properties in props: true attribute
{
    
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile, 
	props: true
}

1234567
  • Pass parameters as before
  • stay Profile.vue Receive parameters to add... To the target component props attribute
<template>
  <div>
     Personal information 
    {
   { id }}
  </div>
</template>
<script>
    export default {
      props: ['id'],
      name: "UserProfile"
    }
</script>
<style scoped>
</style>

123456789101112131415
  • test
     Insert picture description here

9.4.2 Redirect

Vue Redirection in is used when the paths are different but the components are the same

  • stay router/index.js Configure redirection path
{
    
  path: '/main',
  name: 'Main',
  component: Main
},
{
    
  path: '/goHome',
  redirect: '/main'
}

12345678910
  • View added
<el-menu-item index="1-3">
    <!-- Where to insert -->
    <router-link to="/goHome"> Back to the home page </router-link>
</el-menu-item>

12345

9.5 Routing mode 、404 And routing hook

9.5.1 Routing mode

There are two routing modes

  • hash: Path belt # Symbol , Such as http://localhost/#/login
  • history: The path does not take # Symbol , Such as http://localhost/login

Modify routing configuration

export default new VueRouter({
    
  mode:'history',
  routes: []
  )}

12345

Modify in the routing configuration

9.5.2 404 page

  • Create a NotFound.vue View
<template>
  <div>
    <h1>404, Your page is lost </h1>
  </div>
</template>
<script>
    export default {
        name: "NotFound"
    }
</script>
<style scoped>
</style>

12345678910111213
  • Modify routing configuration index.js
import NotFound from '../views/NotFound'
{
    
   path: '*',
   component: NotFound
}
12345
  • test

 Insert picture description here

9.5.3 Routing hook

In addition to the previous hook function, there are two hook functions

beforeRouteEnter: Execute before entering the route
beforeRouteLeave: Execute before leaving the route

  • stay Profile.vue Use
<script>
    export default {
        name: "UserProfile",
        beforeRouteEnter: (to, from, next) => {
            console.log(" Ready to go to the personal information page ");
            next();
        },
        beforeRouteLeave: (to, from, next) => {
            console.log(" Ready to leave the personal information page ");
            next();
        }
    }
</script>
12345678910111213

Parameter description :

to: Route information about the route to jump

from: Path information before path jump
next: Routing control parameters
next() Jump to the next page
next(’/path’) Change the jump direction of the route , Make it jump to another route
next(false) Return to the original page
next((vm)=>{}) Only in beforeRouteEnter Available in the ,vm Is a component instance

  • Make asynchronous requests in hook functions

    • install Axios
    cnpm install --save vue-axios
    
    12
    
    • main.js quote Axios
    import axios from 'axios'
    import VueAxios from 'vue-axios'
    Vue.use(VueAxios, axios)
    
    1234
    
    • Prepare the data
    {
          
      "name": "cv warrior ",
      "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
      "page": 1,
      "isNonProfit": true,
      "address": {
          
        "street": " Han guangmen ",
        "city": " Xi'an, Shaanxi ",
        "country": " China "
      },
      "links": [
        {
          
          "name": "bilibili",
          "url": "https://bilibili.com"
        },
        {
          
          "name": "cv warrior ",
          "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
        },
        {
          
          "name": " Baidu ",
          "url": "https://www.baidu.com/"
        }
      ]
    }
    12345678910111213141516171819202122232425
    

    explain : Only ours static The files in the directory can be accessed , So we put the static files in this directory

    • stay beforeRouteEnter Make asynchronous requests in
    <script>
        export default {
            name: "UserProfile",
            beforeRouteEnter: (to, from, next) => {
                console.log(" Ready to go to the personal information page ");
                next(vm => {
                    // Before entering the route getData Method 
                    vm.getData()
                });
            },
            beforeRouteLeave: (to, from, next) => {
                console.log(" Ready to leave the personal information page ");
                next();
            },
            //axios
            methods: {
                getData: function () {
                    this.axios({
                        method: 'get',
                        url: 'http://localhost:8080/static/mock/data.json'
                    }).then(function (response) {
                        console.log(response)
                    })
                }
            }
        }
    </script>
    123456789101112131415161718192021222324252627
    
    • test
       Insert picture description here

copyright notice
author[Shuai dada's structural road],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240823356542.html

Random recommended