Summary of the vue stage (vue basics)

Table of contents

1. What is vue

2. What is mvc and mvvm

3. The difference between framework and library

4. Interpolation expressions

5. The vue instruction prevents the page from flickering

6. The difference between v-html and v-text of vue instructions

7.vue directive - property binding and shorthand

8.vue instruction - event binding and shorthand

9.vue event modifier

10.vue directive - two-way data binding

11.vue instruction - loop rendering

12.vue instruction - show hide

13. Why does the vue command -v-for set the key

14.vue binding class method

15.vue binding style method

16.vue filter global and local declaration methods and use

17.vue keyboard modifier usage

18.vue keyboard modifier setting alias

19.vue custom directive global and local declaration methods and use

20. What are the Vue lifecycle hook functions?

21. How does vue-resource send get, post requests

22. What is the third parameter of the post request sent by vue-resource?

23.axios sends get, post request

24. What is the built-in parameter object used by axios to send post request

25. What are the transition animation class names in vue?

26. Transition animation in vue combined with third-party plug-ins

27. The use of hook functions in transition animations in vue

28. How to set v-for list animation in vue

30. How to pass values ​​from parent components to child components in Vue

31. How to pass values ​​from child components to parent components in Vue

32. How to use slots in Vue, the difference between the two slots

33. The difference between front-end routing and back-end routing

34. How to use routing in vue

35. There are two ways of routing jump, declarative, functional

36. There are two ways of routing parameters, declarative and functional

37. Route nesting

38. Routing highlight

39. Route redirection

40. Use of ref

41. Attribute calculation, attribute monitoring

1. What is vue


vue is a progressive framework for building user interfaces. Unlike other heavyweight frameworks, vue adopts a bottom-up incremental development design. The core library of vue only focuses on the view layer, which is not only easy to use, but also easy to use with third-party libraries or Integration of existing projects

2. What is mvc and mvvm


mvc is a layered development concept for the backend

mvvm is the concept of the front-end view layer, which mainly focuses on the separation of the view layer, that is to say: mvvm divides the front-end view layer into three parts: Model, View, and ViewModel

3. The difference between framework and library


Framework: It is a complete solution; it is relatively intrusive to the project. If the project needs to replace the framework, the entire project needs to be restructured.

Library (plug-in): Provides a small function, which is less intrusive to the project. If a library cannot fulfill certain requirements, it can be easily switched to other libraries to achieve the requirements.

4. Interpolation expressions


Interpolation expression {{}}, you can insert some content before and after

5. The vue instruction prevents the page from flickering


v-cloak: v-cloak exists before vue is loaded, and v-cloak is hidden after vue is loaded. This feature can be used to prevent page flickering

6. The difference between v-html and v-text of vue instructions


v-html can recognize rich text

7.vue directive - property binding and shorthand


v-bind instruction, which can be directly abbreviated as colon

8.vue instruction - event binding and shorthand


v-on directive, which can be abbreviated as @

9.vue event modifier


.stop stops bubbling
.prevent prevent default event
.capture Add event listener to capture mode
.self only fires the callback when the event fires on the element itself (i.e. not a child element)
.once event fires only once


10.vue directive - two-way data binding


v-model : role: data two-way binding

  : Note: Only form controls can be bound

11.vue instruction - loop rendering


v-for

Traverse the array, parameters (item,index) in list
Traverse objects, parameters (value,key,index) in list
Traverse numbers, num in 10 (1~10)
key needs to be set when using v-for
Bind the UI element to each record in the array
key can only be a string or a number
key must be unique


12.vue instruction - show hide


v-if and v-show

the difference:
v-if removes dom elements
v-show set display:none
Application scenarios:
v-if can be used when v-if is only modified once
v-show can be used when v-show switches frequently


13. Why does the vue command -v-for set the key


As of 2.2.0+, the key is now required when using v-for in a component.

When Vue.js is using v-for to update a list of rendered elements, it defaults to the "reuse-in-place" strategy. If the order of the data items is changed, instead of moving the DOM elements to match the order of the data items, Vue will simply reuse each element here, and make sure it shows each element that has been rendered at a specific index.

In order to give Vue a hint so that it can keep track of the identity of each node and thus reuse and reorder existing elements, you need to provide each item with a unique key property.

14.vue binding class method


array
Miki Expression
Array built-in object (the key of the object is the name of the style, and the value is of type Boolean)
directly through the object


15.vue binding style method


Write style objects directly on the element in the form of :style
Define the style object into data and reference it directly to :style
Define styles on data
In the element, the style object is applied to the element in the form of property binding
Pass arrays in :style, referencing style objects on multiple data
Define styles on data
In the element, the style object is applied to the element in the form of property binding


16.vue filter global and local declaration methods and use

http://t.csdn.cn/3Vci4

17.vue keyboard modifier usage

http://t.csdn.cn/3Vci4

18.vue keyboard modifier setting alias

http://t.csdn.cn/3Vci4

19.vue custom directive global and local declaration methods and use

http://t.csdn.cn/3Vci4

20. What are the Vue lifecycle hook functions?


What are the characteristics of each stage of the vue life cycle hook function?

http://t.csdn.cn/H4I8r

21. How does vue-resource send get, post requests


installation method

Use cdn:

    <script     src="https://cdn.bootcdn.net/ajax/libs/vue-resource/1.5.3/vue-resource.min.js"></script>

Directly in the page, through the script tag, import the script file of vue-resource;
Note: The order of reference is - first refer to the script file of Vue, and then refer to the script file of vue-resource
get request

getInfo() { // get data by get
this.$http.get('http://yapi.shangyuninfo.com/mock/36/web02/category').then(res => {
  console.log(res.body);
})
}
post request

postInfo() {
var url = 'http://yapi.shangyuninfo.com/mock/36/web02/list/goods/category';
// The post method accepts three parameters:
// Parameter 1: The URL address to request
// parameter 2: the data object to send
// Parameter 3: Specify the encoding type of post submission as application/x-www-form-urlencoded
this.$http.post(url, {categoryId: 'zs' }, { emulateJSON: true }).then(res => {
  console.log(res.body);
});
}


22. What is the third parameter of the post request sent by vue-resource?


/Parameter 3: Specifies that the encoding type submitted by the post is application/x-www-form-urlencoded

written as { emulateJSON: true }

23.axios sends get, post request


Vue.js version 2.0 recommends using axios to complete ajax requests.

Axios is a Promise-based HTTP library that can be used in browsers and node.js.

installation method

Use cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

or

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

Use npm:

npm install axios

get request and post request

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
  <script src="./vue-2.4.0.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/css/swiper.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/js/swiper.js"></script>
  <style>
    .swiper-container {
          width: 100%;
          height: 300px;
      }
 
    .swiper-container img {
        width: 100%;
        height: 100%;
    }
    .qqq{
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin: auto;
      width: 90%;
      height: 100px;
      margin: 88px 0px;
    }
    .qqq>div{
      width: 20%;
    }
    .qqq>div img{
      width: 164%;
    }
  </style>
</head>
<body>
  <div id='app'>
    <!-- carousel -->
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="item in imgList" :key="item.id">
            <!-- <img :src="item.imgUrlPc" alt=""> -->
            <img :src="`${item.imgUrlPc}`" alt="">
          </div>
        </div>
        <!-- Pager if needed -->
        <div class="swiper-pagination"></div>
      
        <!-- Navigation buttons if needed -->
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
      
      </div>
      <!--  -->
      <header>
        <a v-for="item in headerLink" href=""> ---{{item.subjectTitle}}---</a>
      </header>
      <!-- course -->
      <div>
          <div v-for="item1 in Cclass" class="qqq">
            <div v-for="item in item1">
              <a href="">
                <div style="width: 100px; height:100px;"><img :src="item.coverFileUrl" alt=""></div>
                <div class="bFather"><b>{{item.courseTitle}}</b></div>
                <div><span>common{{item.subSectionNum}}lesson|{{item.participationsCount}}people sign up</span></div>
                <div>
                  <span v-if="item.isfree == 1"> free</span>
                  <span v-else-if="item.isDiscount == 1"> <del> {{item.coursePrice}} </del> {{item.discountPrice}}</span>
                  <span v-else> {{item.coursePrice}}</span>
                </div>
              </a>
            </div>
          </div>
      </div>
 
 
 
 
    <footer>
      <a  v-for="item in footeLlink"  :href="item.dictValue">------{{item.dictLabel}}------</a>
    </footer>
 
  </div>
 
 
  <script>
  const vm = new Vue({
    el: '#app',
    data: {
      baseurl:'http://1.117.81.216:8086',
      imgSrc:'',
      imgList:'',
      FreeClasses:[],
      boutiqueClasses:[],
      Cclass:[],
    },
    methods: {
       // Request a Course List
      getCourseList(type = 'free', pageSize = 5, pageNum = 1) {
        let formurl2 = new URLSearchParams()
        formurl2.append('type', type)
        formurl2.append('pageSize', pageSize)
        formurl2.append('pageNum', pageNum)
        // post request
        return axios.post(this.baseurl + "/weChat/applet/course/list/type", formurl2)
      }
    },
    created(){
      // carousel
      axios.get("http://1.117.81.216:8086/weChat/applet/course/banner/list?number=4").then(
        res => {
          console.log(res);
          this.imgSrc =res.data.data[0].imgUrlPc
          this.imgList= res.data.data
          console.log(this.imgList[0].imgUrlPc);
          this.$nextTick(() => {
            var mySwiper = new Swiper('.swiper-container', {
              // direction: 'vertical', // vertical toggle option
              loop: true, // Loop Mode Options
              // Pager if needed
              pagination: {
                el: '.swiper-pagination',
              },
              // Forward and back buttons if needed
              navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
              },
            })
          })
 
        })
      //Free Courses // Premium Courses // Discounted Courses
      this.getCourseList().then(res=>{
        this.Cclass.push(res.data.rows)       
        this.getCourseList('boutique', 5).then(res => {
          this.Cclass.push(res.data.rows)     
          this.getCourseList('discount', 5).then(res => {
            this.Cclass.push(res.data.rows)
          })
        })
      })
 
      //Top Course List
      axios.post(this.baseurl + "/weChat/applet/subject/list", JSON.stringify({enable:1})).then(res => {
        this.headerLink=res.data.rows
      })
      //bottom link
      let forurl = new URLSearchParams()
      forurl.append('dictType','blogroll')
      forurl.append('pageNum',1)
      forurl.append('pageSize',10)
      forurl.append('orderByColumn','dictSort')
      forurl.append('isAsc','asc')
      axios.post(this.baseurl + "/system/dict/data/list/open",forurl).then(res => {
        this.footeLlink = res.data.rows
      })
 
  }
})
  </script>
</body>
</html>

24. What is the built-in parameter object used by axios to send post request


In the post request,
When the request header is a json string and object, it can be directly converted to a json object
When the request header is application/x-www-form-urlencoded, create a URLSearchParams object
When the request header is multipart/form-data, create a FormData object


25. What are the transition animation class names in vue?


    .v-enter
    .v-enter-to
    .v-enter-active
    .v-leave
    .v-leave-to
    .v-leave-active


26. Transition animation in vue combined with third-party plug-ins


Import the animation class library:

<link href="https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">Define transition and properties:

 <transition name="custom-classes-transition" enter-active-class="animate__animated animate__zoomOutDown" leave-active-class="animated bounceOutRight">

<p v-if="show">The First Legion has no secrets</p>

 </transition>

27. The use of hook functions in transition animations in vue


Define the transition component and three hook functions:

<div id="app">

<input type="button" value="toggle animation" @click="isshow = !isshow">
  <transition
  @before-enter="beforeEnter"
  @enter="enter"
  @after-enter="afterEnter">
    <div v-if="isshow" class="show">OK</div>
  </transition>
</div>

Define three methods hook methods:

methods: {

beforeEnter(el) { // callback before animation enters
        el.style.transform = 'translateX(500px)';
      },
enter(el, done) { // callback when the animation is finished
        el.offsetWidth;
        el.style.transform = 'translateX(0px)';
        done();
      },
afterEnter(el) { // Callback after animation entry is complete
        this.isshow = !this.isshow;
      }

}

Define animation transition duration and style:

.show{

transition: all 0.4s ease;

}

28. How to set v-for list animation in vue


Define the transition style:

 <style>

        .v-enter{
            transform: translateX(-200px);

        }

        .v-enter-to{
            transform: translateX(0px);

        }

        .v-enter-active{
            transition: all 2s;

        }

        .v-leave{
            transform: translateX(0px);

        }

        .v-leave-to{
            transform: translateX(200px);

        }

        .v-leave-active{
            transition: all 2s;

        }

    </style>

Define the DOM structure in which the list of v-for loops needs to be wrapped with the transition-group component:

<div id='app'>

<button @click="flag = !flag"> click me</button>

        <transition-group tag="ul">

            <div v-if="flag"  v-for="item in 9" :key="item">

                {{item}}

            </div>

        </transition-group>

    </div>

Define the structure in the VM:

const vm = new Vue({
        el: '#app',

        data: {
            flag:true

        },

        methods: {
        },

    })
 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style>
        .v-enter{
            transform: translateX(-200px);
        }
        .v-enter-to{
            transform: translateX(0px);
        }
        .v-enter-active{
            transition: all 2s;
        }
        .v-leave{
            transform: translateX(0px); 
        }
        .v-leave-to{
            transform: translateX(200px);
        }
        .v-leave-active{
            transition: all 2s;
        }
    </style>
</head>
<body>
    <div id='app'>
        <button @click="flag = !flag"> I point</button>
        <transition-group tag="ul">
            <div v-if="flag"  v-for="item in 9" :key="item">
                {{item}}
            </div>
        </transition-group>
    </div>
 
 
    <script>
    const vm = new Vue({
        el: '#app',
        data: {
            flag:true
        },
        methods: {
        },
    })
    </script>
</body>
</html>

29. How to declare components in Vue

http://t.csdn.cn/kGV9p

30. How to pass values ​​from parent components to child components in Vue

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
  <script src="./allLib/vue/vue-2.4.0.js"></script>
  <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <style>
      ul {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
    
      li {
        list-style: none;
        width: 18%;
      }
    
      li img {
        width: 100%;
      }
      h2{
        text-align: center;
      }
    </style>
</head>
<body>
  <div id='app'>
    
    <courseclass :type="type11" page-size="10"> 
      😊😊😊😊😊😊
      <template v-slot:header>free</template>
    </courseclass>
    <courseclass type="boutique">
      😍😍😍😍😍😍😍
      <template v-slot:header>boutique</template>
    </courseclass>
    <courseclass type="discount">
      😁😁😁😁😁😁😁 
      <template v-slot:header>pay</template>
    </courseclass>
  </div>
  <template id="course">
    <div>
      <slot></slot>
      <h2>
        <slot name="header"></slot> course
      </h2>
      <ul>
        <li v-for="item in courselist">
          <img :src="item.coverFileUrl" alt="">
          <div>{{item.courseTitle}} </div>
          <div> {{item.learningNum}}</div>
          <div>free </div>
        </li>
      </ul>
    </div>
  </template>
 
  <script>
    Vue.component('courseclass',{
      template:'#course',
      data(){
        return{
          courselist:[]
        }
      },
      props:{
        type:String,
        pageSize:Number,
        // pageSize:[Number,String],
        pageSize:{
          type:[Number,String],
          default(){
            return 5
          }        
        }
      },
      methods:{
        getCourseList(type='free',pageSize=5,pageNum=1){
          let formurl = new URLSearchParams()
          formurl.append('type',type)
          formurl.append('pageSize', pageSize)
          formurl.append('pageNum', pageNum)
          return axios.post('http://1.117.81.216:8086/weChat/applet/course/list/type',formurl)
        }
      },
      created(){
        this.getCourseList(this.type,this.pageSize,1).then(
          res=>{
            this.courselist= res.data.rows
          }
        )
      }
    })
  const vm = new Vue({
    el: '#app',
    data: {
      type11:'free'
    },
    methods: {
    },
  })
  </script>
</body>
</html>

31. How to pass values ​​from child components to parent components in Vue

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- <script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
</head>
<body>
  <!-- The child component calls the method of the parent component
  1.Register an event in the parent component for the referenced child component (the name of this event is custom)
  2.Child components can trigger this event $emit('event name')
  
  Child component passes data to parent component
  1.$emit The second parameter of the method can define the content passed by the child component to the parent component
  2.How to get this content in the parent component
  2.1 This method of the parent component has no custom parameters. You can get it by adding this parameter directly to the method of the parent component.
  2.2 The parent component has custom parameters that can be passed in $event You can also get the data passed by the child components. pass $event Only the first parameter can be passed. -->
  <div id='app'>
    <father></father>
  </div>
 
 
  <template id='father' ref="fatherxx">
    <div>
      father ---{{fromSon}}
      {{fathmsg}}
      <son  @getsonvalue="getsonvaluess($event,'hello')"></son>
      <son @getvalue2="getvalue22"></son>
    </div>
  </template>
  <template id='son'>
    <div>
      son
      <button @click="tofather">Click my son to pass on the father</button>
      <button @click="tofather2">Click my son to pass on the father 2</button>
      <button @click="toref">toref</button>
    </div>
  </template>
 
 
  <script>
  Vue.component('father',{
    template:'#father',
    data(){
        return{
          fromSon: '',
          fathmsg:'father content',
          hello3: '333'
        }
    },
    methods: {
      getsonvaluess(data, data2) {
        // console.log(event);
        console.log(data);
        console.log(data2);
 
        this.fromSon = data
      },
      getvalue22(v){
        console.log(v);
      }
    },
  })
  Vue.component('son', {
      template: '#son',
      data(){
        return {}
      },
      methods: {
        tofather(){
          this.$emit('getsonvalue','The value passed from the child component to the parent component')
        },
        tofather2() {
          this.$emit('getvalue2', 'The value passed from the child component to the parent component is 2222')
        },
        toref(){
          this.$refs.fatherxx.fathmsg='123123123'
        }
      }
    })
  const vm = new Vue({
    el: '#app',
    data: {
    },
    methods: {
    },
    beforeCreate(){
    },
    created(){
    },
    beforeMount(){
    },
    mounted(){
    },
    beforeUpdate(){
    },
    updated(){
    },
  })
  </script>
</body>
</html>

32. How to use slots in Vue, the difference between the two slots

http://t.csdn.cn/N3Zcs

33. The difference between front-end routing and back-end routing


Back-end routing: For ordinary websites, all hyperlinks are URL addresses, and all URL addresses correspond to corresponding resources on the server
Front-end routing: For single-page applications, switching between different pages is mainly achieved through the hash(#) in the URL. At the same time, hash has a feature: the HTTP request will not contain hash-related content; therefore, The page jump in the single-page program is mainly implemented by hash;
In a single-page application, this way of switching pages through hash changes is called front-end routing (different from back-end routing)


34. How to use routing in vue


installation of routing
   <script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>

Basic use of routing

Introduce the js file, this js needs to be placed behind the js of vue and installed automatically (a VueRouter construction method is provided)
Create a route new VueRouter(), the accepted parameter is an object
Configure the attribute routes:[] in the instantiated object, the object in this array contains the path attribute and the component attribute
The path attribute is the address of the url, and the component attribute is the displayed component (the object passed to the component)
The created route needs to be associated with the vue instance
Where is the routed component displayed <router-view></router-view>
case

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 1. introduce js file, this js need to be placed vue of js Later, automatic installation (provides a VueRouter construction method) -->
    <script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
 
    <style>
        .router-link-active{
            font-size: 30px;
            color: hotpink;
        }
        .myactive{
            font-size: 40px;
            color: red;
        }
 
 
    </style>
    
</head>
<body>
    <div id='app'>
 
        <!-- Basic use of routing
1 introduce js file, this js need to be placed vue of js Later, automatic installation (provides a VueRouter construction method)
2 Create route new VueRouter(),The accepted argument is an object
3 Configure properties in the instantiated object routes:[],The objects in this array contain path properties and component Attributes
4path property is url the address of,component The property is the displayed component (the object passed to the component)
5 The route created needs and vue Link to the instance
6 Where the routed component is displayed -->
<!-- Declarative jump   -->
<router-link to="/index">index </router-link>
<router-link :to="{name:'index'}">index </router-link>
<router-link to="/detail">go to details </router-link>
<button @click="todetail"> q go to details page</button>
<button @click="toMine"> Personal center page</button>
<!-- Reserved display area -->
<router-view></router-view>
    </div>
    <template id="index">
        <div>
            front page
            <!-- <a href="#/detail">go to details</a> -->
            <router-link to="/detail">go to details </router-link>
            <router-link to="/detail?id=104&name='zs'">go to details 2222 </router-link>
            <router-link :to="{path:'/detail',query:{id:103,name:'zs'}}">go to details </router-link>
            <router-link :to="{name:'my',params:{userid:234}}"> go to personal center </router-link>
            <!-- wrong spelling -->
            <router-link :to="{name:'my'}"> go to personal center </router-link>
 
        </div>
    </template>
 
    <template id="detail">
        <div>
            Details page
        </div>
    </template>
    <template id="mine">
        <div>
            personal page
        </div>
    </template>
 
 
    <script>
        let index = {
            template: '#index',
        }
        let detail = {
            template: '#detail',
            created(){
                console.log(this);
                
                console.log(this.$route.query.id);
            }
        }
        let mine = {
            template: '#mine',
            created(){
                console.log(this);
                
                console.log(this.$route.params);
            }
        }
 
 
 
        // 2. Create a route instance object
         const router = new VueRouter({
            // 3. Create a mapping relationship
            routes:[
                // route redirection
                {
                    path:'/',
                    redirect:'/index'
                },
                {
                    path:'/index',
                    component: index,
                    name:'index'
                },
                {
                    path:'/detail',
                    component: detail,
                },
                // path parameter
                {
                    path:'/mine/:userid',
                    component:mine,
                    name:'my'
                }
            ],
            // custom route highlighting
            linkActiveClass:"myactive"
        });
 
    const vm = new Vue({
        // 4. Mount the route on vue
        // router:router,
        router,
        el: '#app',
        data: {
        },
        watch:{
            $route(){
                console.log(this.$route);
 
                if( this.$route.name =='my'){
                    alert('welcome to personal center')
                }
            }
        },
        methods: {
            // functional jump
            todetail(){
                // this.$router.push('/detail')
                this.$router.push({path:'/detail'})
                this.$router.push({path:'/mine',query:{id:104,name:'lisi'}})
            },
            toMine(){
                this.$router.push({
                    name:"my",
                    params:{userid:999}
                })
            }
        },
        beforeCreate(){},
        created(){},
        beforeMount(){},
        mounted(){},
        beforeUpdate(){},
        updated(){},
        beforeDestroy(){},
        destroyed(){},
    })
    </script>
</body>
</html>

35. There are two ways of routing jump, declarative, functional


Declarative: write directly after to

<router-link to="/detail?id=104&name='zs'">Go to details 2222 </router-link>

functional

<button @click="todetail"> go to detail page</button>

// functional jump

            todetail(){
                this.$router.push({path:'/detail'})

                this.$router.push({path:'/mine',query:{id:104,name:'lisi'}})

            },

36. There are two ways of routing parameters, declarative and functional


1. Add ?parameter name=parameter value after the url by query

Get parameters: $route.query.Parameter name

2. Use browser parameters to pass parameters

When setting the route / route address/: parameter name
Get parameters $route.params.Parameter name


37. Route nesting


When declaring a route, set children. This is an array of children, and the array is a routing object.
The children's component will be rendered in the <router-view> of its parent component

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 1. introduce js file, this js need to be placed vue of js Later, automatic installation (provides a VueRouter construction method) -->
    <script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
 
    <style>
        .router-link-active{
            font-size: 30px;
            color: hotpink;
        }
        .myactive{
            font-size: 40px;
            color: red;
        }
 
 
    </style>
    
</head>
<body>
    <div id='app'>
 
        <!-- Basic use of routing
1 introduce js file, this js need to be placed vue of js Later, automatic installation (provides a VueRouter construction method)
2 Create route new VueRouter(),The accepted argument is an object
3 Configure properties in the instantiated object routes:[],The objects in this array contain path properties and component Attributes
4path property is url the address of,component The property is the displayed component (the object passed to the component)
5 The route created needs and vue Link to the instance
6 Where the routed component is displayed -->
<!-- Declarative jump   -->
<router-link to="/index">index </router-link>
<router-link :to="{name:'index'}">index </router-link>
<router-link to="/detail">go to details </router-link>
 
 
<button @click="todetail"> q go to details page</button>
<button @click="toMine"> Personal center page</button>
<!-- Reserved display area -->
<router-view></router-view>
    </div>
 
    <template id="index">
        <div>
            front page
 
 
            <router-link to="/detail">go to details </router-link>
            <router-link to="/detail?id=104&name='zs'">go to details 2222 </router-link>
            <router-link :to="{path:'/detail',query:{id:103,name:'zs'}}">go to details </router-link>
 
 
            <router-link :to="{name:'my',params:{userid:234}}"> go to personal center </router-link>
            <!-- wrong spelling -->
            <router-link :to="{name:'my'}"> go to personal center </router-link>
 
        </div>
    </template>
 
    <template id="detail">
        <div>
            Details page
            <router-link to="/detail/play"> play</router-link>
 
            <router-view></router-view>
 
        </div>
    </template>
 
    <template id="course">
        <div>
            Course Information Buffer
 
           
        </div>
    </template>
    <template id="play">
        <div>
            Course information playback
        </div>
    </template>
 
    <template id="mine">
        <div>
            personal page
        </div>
    </template>
 
 
    <script>
        let play = {
            template: '#play',
        }
        let course = {
            template: '#course',
        }
        let index = {
            template: '#index',
        }
        let detail = {
            template: '#detail',
            created(){
                console.log(this);
                
                console.log(this.$route.query.id);
            }
        }
        let mine = {
            template: '#mine',
            created(){
                console.log(this);
                
                console.log(this.$route.params);
            }
        }
 
 
 
        // 2. Create a route instance object
         const router = new VueRouter({
            // 3. Create a mapping relationship
            routes:[
                // route redirection
                {
                    path:'/',
                    redirect:'/index'
                },
                {
                    path:'/index',
                    component: index,
                    name:'index'
                    
                },
                {
                    path:'/detail',
                    component: detail,
                    // route nesting
                    children:[
                        {
                            path:"/play",
                            component:play
 
                        },
                        {
                            path:"course",
                            component:course
                        },
                    ]
                },
                // path parameter
                {
                    path:'/mine/:userid',
                    component:mine,
                    name:'my'
                }
            ],
            // custom route highlighting
            linkActiveClass:"myactive"
        });
 
    const vm = new Vue({
        // 4. Mount the route on vue
        // router:router,
        router,
        el: '#app',
        data: {
        },
        methods: {
            // functional jump
            todetail(){
                // this.$router.push('/detail')
                this.$router.push({path:'/detail'})
                this.$router.push({path:'/mine',query:{id:104,name:'lisi'}})
            },
            toMine(){
                this.$router.push({
                    name:"my",
                    params:{userid:999}
                })
            }
        },
        beforeCreate(){},
        created(){},
        beforeMount(){},
        mounted(){},
        beforeUpdate(){},
        updated(){},
        beforeDestroy(){},
        destroyed(){},
    })
    </script>
</body>
</html>

38. Routing highlight

Highlight the selected route

  1. Set router-link-active directly using the default style
  2. Custom style configuration linkActiveClass:'custom class name'

39. Route redirection

redirect can redirect the route

                 // route redirection
                {
                    path:'/',
                    redirect:'/index'
                },

40. Use of ref

get dom node

  1. Putting the ref attribute on the dom node can be understood as giving a name to the dom node.
  2. After adding ref, there is a reference to this element in the $refs attribute.
  3. Get this dom element through the $refs attribute of the vue instance.

get component

  1. Putting the ref attribute on the component can be understood as giving the component a name.
  2. After adding ref, there is a reference to this component in the $refs attribute.
  3. Get the reference of this component through the $refs attribute of the vue instance, and then you can call the method of the subcomponent through this reference, or get the data of the subcomponent.

41. Attribute calculation, attribute monitoring

Watch usage

monitor data Changes in properties:
<div id="app">
  <input type="text" v-model="firstName"> +
  <input type="text" v-model="lastName"> =
  <span>{{fullName}}</span>
</div>
 
<script>
  // Create Vue instance, get ViewModel
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'jack',
      lastName: 'chen',
      fullName: 'jack - chen'
    },
    methods: {},
    watch: {
      'firstName': function (newVal, oldVal) { // The first parameter is the new data and the second parameter is the old data
        this.fullName = newVal + ' - ' + this.lastName;
      },
      'lastName': function (newVal, oldVal) {
        this.fullName = this.firstName + ' - ' + newVal;
      }
    }
  });
</script>
 
Listen for changes to the route object:
<div id="app">
  <router-link to="/login">Log in</router-link>
  <router-link to="/register">register</router-link>
 
  <router-view></router-view>
</div>
<script>
  var login = Vue.extend({
    template: '<h1>login component</h1>'
  });
 
  var register = Vue.extend({
    template: '<h1>Register components</h1>'
  });
 
  var router = new VueRouter({
    routes: [
      { path: "/login", component: login },
      { path: "/register", component: register }
    ]
  });
 
  // Create Vue instance, get ViewModel
  var vm = new Vue({
    el: '#app',
    data: {},
    methods: {},
    router: router,
    watch: {
      '$route': function (newVal, oldVal) {
        if (newVal.path === '/login') {
          console.log('This is the login component');
        }
      }
    }
  });
</script>

Computed usage

By default only getter The computed property of :
<div id="app">
  <input type="text" v-model="firstName"> +
  <input type="text" v-model="lastName"> =
  <span>{{fullName}}</span>
</div>
 
<script>
  // Create Vue instance, get ViewModel
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'jack',
      lastName: 'chen'
    },
    methods: {},
    computed: { // Computed property; Features: When any of the data properties in the computed property are changed, the recalculation of the computed property will be re-triggered, thereby updating the value of fullName
      fullName() {
        return this.firstName + ' - ' + this.lastName;
      }
    }
  });
</script>
 
Defined with getter and setter The computed property of :
<div id="app">
  <input type="text" v-model="firstName">
  <input type="text" v-model="lastName">
  <!-- Click the button to reset the computed property fullName assign -->
  <input type="button" value="Revise fullName" @click="changeName">
 
  <span>{{fullName}}</span>
</div>
 
<script>
  // Create Vue instance, get ViewModel
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'jack',
      lastName: 'chen'
    },
    methods: {
      changeName() {
        this.fullName = 'TOM - chen2';
      }
    },
    computed: {
      fullName: {
        get: function () {
          return this.firstName + ' - ' + this.lastName;
        },
        set: function (newVal) {
          var parts = newVal.split(' - ');
          this.firstName = parts[0];
          this.lastName = parts[1];
        }
      }
    }
  });
</script>

The difference between method, computed and watch

The results of computed properties are cached and recomputed unless the dependent reactive properties change. Mainly used as an attribute, when used without ();
The methods method represents a specific operation, mainly writing business logic;
watch an object, the key is the expression to be observed, and the value is the corresponding callback function. It is mainly used to monitor the changes of some specific data, so as to perform some specific business logic operations; it can be regarded as a combination of computed and methods
 

Tags: Javascript Front-end Vue.js

Posted by nublet on Sun, 25 Sep 2022 21:22:35 +0300