vue阶段总结(vue基础)

目录

1.什么是vue

2.什么是mvc和mvvm

3.框架和库的区别

4.插值表达式

5.vue指令防止页面闪烁

6.vue指令v-html和v-text的区别

7.vue指令-属性绑定及简写

8.vue指令-事件绑定及简写

9.vue事件修饰符

10.vue指令-双向数据绑定

11.vue指令-循环渲染

12.vue指令-显示隐藏

13. vue指令-v-for为什么设置key

14.vue绑定class方式 

15.vue绑定style方式 

16.vue过滤器全局和局部声明方式及使用 

17.vue键盘修饰符使用 

18.vue键盘修饰符设置别名

19.vue自定义指令全局和局部声明方式及使用

 20.vue生命周期钩子函数有哪些?

vue生命周期钩子函数各阶段特点,什么作用?

21.vue-resource如何发送get,post请求

 22.vue-resource发送post请求第三个参数写什么

23.axios发送get,post请求

24.axios发送post请求使用内置参数对象是什么

 在post请求时,

请求头为json字符串和对象时,直接转为json对象即可

请求头为application/x-www-form-urlencoded时,创建一个URLSearchParams对象

请求头为multipart/form-data 时,创建一个FormData对象

25.vue中过渡动画类名有哪些 

26.vue中过渡动画结合第三方插件使用

27.vue中过渡动画中钩子函数的使用

28.vue中如何设置v-for列表动画

29.vue中如何声明组件

30.vue中如何父组件给子组件传值

31.vue中如何子组件给父组件传值 

32.vue中如何使用插槽,两种插槽的区别

33.前端路由和后端路由的区别

 34.vue中如何使用路由

35.路由跳转两种方式,声明式,函数式 

36.路由传参两种方式,声明式,函数式

37.路由嵌套 

 38.路由高亮

 39.路由重定向

40.ref的使用 

 41.属性计算,属性监听


1.什么是vue

vue是一套构建用户界面的渐进式框架,与其他重量级框架不同,vue采用自底向上增量开发的设计,vue的核心库只注视图层,不仅易于上手,还便于与第三方库或者既有项目整合

2.什么是mvc和mvvm

mvc是后端的分层开发概念

mvvm是前端视图层的概念,主要关注视图层分离,也就是说:mvvm把前端的视图层,分为了三部分Model、View、ViewModel

3.框架和库的区别

框架:是一套完整的解决方案;对项目的侵入性比较大,项目如果需要更换框架,则需要重新架构整个项目。

库(插件):提供某一个小功能,对项目的侵入性较小,如果某个库无法完成某些需求,可以很容易切换到其他库实现需求。

4.插值表达式

插值表达式{{}},可以在前后插入一些内容

5.vue指令防止页面闪烁

v-cloak:在vue加载之前v-cloak是存在,vue加载结束之后v-cloak就隐藏了,利用这个特性可以实现:防止页面闪烁

6.vue指令v-html和v-text的区别

v-html可以识别富文本

7.vue指令-属性绑定及简写

v-bind指令,可以直接简写为冒号

8.vue指令-事件绑定及简写

v-on指令,可以简写为@

9.vue事件修饰符

  1. .stop   阻止冒泡
  2. .prevent   阻止默认事件
  3. .capture   添加事件监听转为捕获模式
  4. .self   只当事件在该元素本身(比如不是子元素)触发时触发回调
  5. .once   事件只触发一次

10.vue指令-双向数据绑定

v-model   :作用:数据双向绑定

                :注意:只能绑定表单控件

11.vue指令-循环渲染

v-for

  1. 遍历数组,参数(item,index) in list
  2. 遍历对象,参数(value,key,index) in list
  3. 遍历数字,num in 10 (1~10)
  4. key在使用v-for的时候都需要去设置key 
  • 让界面元素和数组里的每个记录进行绑定
  • key只能是字符串或者数字
  • key必须是唯一的

12.vue指令-显示隐藏

v-if与v-show

  1. 区别:
    1. v-if删除dom元素
    2. v-show设置display:none
  2. 应用场景:
    1. v-if只修改一次的时候可以使用v-if
    2. v-show频繁切换的时候可以使用v-show

13. vue指令-v-for为什么设置key

2.2.0+ 的版本里,当在组件中使用 v-for 时,key 现在是必须的。

当 Vue.js 用 v-for 正在更新已渲染过的元素列表时,它默认用 “就地复用” 策略。如果数据项的顺序被改变,Vue将不是移动 DOM 元素来匹配数据项的顺序, 而是简单复用此处每个元素,并且确保它在特定索引下显示已被渲染过的每个元素。

为了给 Vue 一个提示,以便它能跟踪每个节点的身份,从而重用和重新排序现有元素,你需要为每项提供一个唯一 key 属性。

14.vue绑定class方式 

  1. 数组
  2. 三木表达式
  3. 数组内置对象(对象的键是样式的名字,值是Boolean类型)
  4. 直接通过对象

15.vue绑定style方式 

  1. 直接在元素上通过 :style 的形式,书写样式对象
  2. 将样式对象,定义到 data 中,并直接引用到 :style 中
    1. 在data上定义样式
    2. 在元素中,通过属性绑定的形式,将样式对象应用到元素中
  3. 在 :style 中通过数组,引用多个 data 上的样式对象
    1. 在data上定义样式
    2. 在元素中,通过属性绑定的形式,将样式对象应用到元素中

16.vue过滤器全局和局部声明方式及使用 

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

17.vue键盘修饰符使用 

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

18.vue键盘修饰符设置别名

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

19.vue自定义指令全局和局部声明方式及使用

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

 20.vue生命周期钩子函数有哪些?

vue生命周期钩子函数各阶段特点,什么作用?

http://t.csdn.cn/H4I8r

21.vue-resource如何发送get,post请求

安装方法

使用 cdn:

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

  1. 直接在页面中,通过script标签,引入vue-resource的脚本文件;
  2. 注意:引用的先后顺序是 - 先引用Vue的脚本文件,再引用vue-resource的脚本文件

get请求

getInfo() { // get 方式获取数据
this.$http.get('http://yapi.shangyuninfo.com/mock/36/web02/category').then(res => {
  console.log(res.body);
})
}

 post请求

postInfo() {
var url = 'http://yapi.shangyuninfo.com/mock/36/web02/list/goods/category';
// post 方法接收三个参数:
// 参数1: 要请求的URL地址
// 参数2: 要发送的数据对象
// 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
this.$http.post(url, {categoryId: 'zs' }, { emulateJSON: true }).then(res => {
  console.log(res.body);
});
}

 22.vue-resource发送post请求第三个参数写什么

/参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded

写为{ emulateJSON: true }

23.axios发送get,post请求

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

安装方法

使用 cdn:

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

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

使用 npm:

npm install axios

get请求和post请求

<!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'>
    <!-- 轮播图 -->
      <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>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>
      
        <!-- 如果需要导航按钮 -->
        <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>
      <!-- 课程 -->
      <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>共{{item.subSectionNum}}节课|{{item.participationsCount}}人报名</span></div>
                <div>
                  <span v-if="item.isfree == 1"> 免费</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: {
       // 请求课程列表
      getCourseList(type = 'free', pageSize = 5, pageNum = 1) {
        let formurl2 = new URLSearchParams()
        formurl2.append('type', type)
        formurl2.append('pageSize', pageSize)
        formurl2.append('pageNum', pageNum)
        // post请求
        return axios.post(this.baseurl + "/weChat/applet/course/list/type", formurl2)
      }
    },
    created(){
      // 轮播图
      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', // 垂直切换选项
              loop: true, // 循环模式选项
              // 如果需要分页器
              pagination: {
                el: '.swiper-pagination',
              },
              // 如果需要前进后退按钮
              navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
              },
            })
          })

        })
      //免费课程//精品课//折扣课程
      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)
          })
        })
      })

      //顶部课程列表
      axios.post(this.baseurl + "/weChat/applet/subject/list", JSON.stringify({enable:1})).then(res => {
        this.headerLink=res.data.rows
      })
      //底部链接
      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.axios发送post请求使用内置参数对象是什么

 在post请求时,

  1. 请求头为json字符串和对象时,直接转为json对象即可

  2. 请求头为application/x-www-form-urlencoded时,创建一个URLSearchParams对象

  3. 请求头为multipart/form-data 时,创建一个FormData对象

25.vue中过渡动画类名有哪些 

  1.     .v-enter
  2.     .v-enter-to
  3.     .v-enter-active
  4.     .v-leave
  5.     .v-leave-to
  6.     .v-leave-active

26.vue中过渡动画结合第三方插件使用

导入动画类库:

<link href="https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">定义 transition 及属性:

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

      <p v-if="show">第一军团没有秘密</p>

 </transition>

27.vue中过渡动画中钩子函数的使用

定义 transition 组件以及三个钩子函数:

<div id="app">

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

定义三个 methods 钩子方法:

methods: {

      beforeEnter(el) { // 动画进入之前的回调
        el.style.transform = 'translateX(500px)';
      },
      enter(el, done) { // 动画进入完成时候的回调

        el.offsetWidth;
        el.style.transform = 'translateX(0px)';
        done();
      },
      afterEnter(el) { // 动画进入完成之后的回调

        this.isshow = !this.isshow;
      }

}

定义动画过渡时长和样式:

.show{

transition: all 0.4s ease;

}

28.vue中如何设置v-for列表动画

 定义过渡样式:

 <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>

定义DOM结构,其中,需要使用 transition-group 组件把v-for循环的列表包裹起来:

<div id='app'>

        <button @click="flag = !flag"> 点我</button>

        <transition-group tag="ul">

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

                {{item}}

            </div>

        </transition-group>

    </div>

定义 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"> 点我</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.vue中如何声明组件

http://t.csdn.cn/kGV9p

30.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>免费</template>
    </courseclass>
    <courseclass type="boutique">
      😍😍😍😍😍😍😍
      <template v-slot:header>精品</template>
    </courseclass>
    <courseclass type="discount">
      😁😁😁😁😁😁😁 
      <template v-slot:header>付费</template>
    </courseclass>
  </div>
  <template id="course">
    <div>
      <slot></slot>
      <h2>
        <slot name="header"></slot> 课程
      </h2>
      <ul>
        <li v-for="item in courselist">
          <img :src="item.coverFileUrl" alt="">
          <div>{{item.courseTitle}} </div>
          <div> {{item.learningNum}}</div>
          <div>免费 </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.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>
  <!-- 子组件调用父组件的方法
  1.在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的)
  2.子组件可以触发这个事件$emit('事件名字')
  
  子组件给父组件传递数据
  1.$emit方法第二个参数可以定义子组件给父组件传递的内容
  2.在父组件中怎么拿到这内容
  2.1 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
  2.2 父组件有自定义参数,可以传入$event也可以拿到子组件传递的数据。通过$event只能传递第一个参数。 -->
  <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">点我子传父</button>
      <button @click="tofather2">点我子传父2</button>
      <button @click="toref">toref</button>
    </div>
  </template>


  <script>
  Vue.component('father',{
    template:'#father',
    data(){
        return{
          fromSon: '',
          fathmsg:'父亲内容',
          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','子组件传给父组件的值')
        },
        tofather2() {
          this.$emit('getvalue2', '子组件传给父组件的值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.vue中如何使用插槽,两种插槽的区别

http://t.csdn.cn/N3Zcs

33.前端路由和后端路由的区别

  1. 后端路由:对于普通的网站,所有的超链接都是URL地址,所有的URL地址都对应服务器上对应的资源
  2. 前端路由:对于单页面应用程序来说,主要通过URL中的hash(#号)来实现不同页面之间的切换,同时,hash有一个特点:HTTP请求中不会包含hash相关的内容;所以,单页面程序中的页面跳转主要用hash实现;
  3. 在单页面应用程序中,这种通过hash改变来切换页面的方式,称作前端路由(区别于后端路由)

 34.vue中如何使用路由

  1. 路由的安装

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

路由的基本使用

  1. 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
  2. 创建路由new VueRouter(),接受的参数是一个对象
  3. 在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性
  4. path属性是url的地址,component属性就是显示的组件(传组件的对象)
  5. 创建的路由需要和vue实例关联一下
  6. 路由到的组件显示在哪个位置<router-view></router-view>

案例

<!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. 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法) -->
    <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'>

        <!-- 路由的基本使用
1引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
2创建路由new VueRouter(),接受的参数是一个对象
3在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性
4path属性是url的地址,component属性就是显示的组件(传组件的对象)
5创建的路由需要和vue实例关联一下
6路由到的组件显示在哪个位置 -->
<!-- 声明式跳转   -->
<router-link to="/index">index </router-link>
<router-link :to="{name:'index'}">index </router-link>
<router-link to="/detail">去详情 </router-link>
<button @click="todetail"> q去详情页</button>
<button @click="toMine"> 个人中心页</button>
<!-- 预留展示区域 -->
<router-view></router-view>
    </div>
    <template id="index">
        <div>
            首页
            <!-- <a href="#/detail">去详情</a> -->
            <router-link to="/detail">去详情 </router-link>
            <router-link to="/detail?id=104&name='zs'">去详情2222 </router-link>
            <router-link :to="{path:'/detail',query:{id:103,name:'zs'}}">去详情 </router-link>
            <router-link :to="{name:'my',params:{userid:234}}"> 去个人中心 </router-link>
            <!-- 错误写法 -->
            <router-link :to="{name:'my'}"> 去个人中心 </router-link>

        </div>
    </template>

    <template id="detail">
        <div>
            详情页
        </div>
    </template>
    <template id="mine">
        <div>
            个人页
        </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. 创建路由实例对象
         const router = new VueRouter({
            // 3.创建映射关系
            routes:[
                // 路由重定向
                {
                    path:'/',
                    redirect:'/index'
                },
                {
                    path:'/index',
                    component: index,
                    name:'index'
                },
                {
                    path:'/detail',
                    component: detail,
                },
                // 路径传参
                {
                    path:'/mine/:userid',
                    component:mine,
                    name:'my'
                }
            ],
            // 自定义路由高亮
            linkActiveClass:"myactive"
        });

    const vm = new Vue({
        // 4.将路由挂载在vue上
        // router:router,
        router,
        el: '#app',
        data: {
        },
        watch:{
            $route(){
                console.log(this.$route);

                if( this.$route.name =='my'){
                    alert('欢迎来到个人中心')
                }
            }
        },
        methods: {
            // 函数式跳转
            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.路由跳转两种方式,声明式,函数式 

声明式:直接写在to后面

<router-link to="/detail?id=104&name='zs'">去详情2222 </router-link>

函数式

<button @click="todetail"> 去详情页</button>

 // 函数式跳转

            todetail(){

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

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

            },

36.路由传参两种方式,声明式,函数式

        1.通过query的方式在url后加?参数名=参数的值

        获取参数:$route.query.参数名

        2.使用浏览器参数的方式传递参数

  1. 设置路由的时候/路由地址/:参数名
  2. 获取参数$route.params.参数名

37.路由嵌套 

  1. 声明路由的时候设置children,这是children是一个数组,数组里是路由对象
  2. 这个children的组件就会渲染在它父组件的<router-view>中
<!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. 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法) -->
    <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'>

        <!-- 路由的基本使用
1引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
2创建路由new VueRouter(),接受的参数是一个对象
3在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性
4path属性是url的地址,component属性就是显示的组件(传组件的对象)
5创建的路由需要和vue实例关联一下
6路由到的组件显示在哪个位置 -->
<!-- 声明式跳转   -->
<router-link to="/index">index </router-link>
<router-link :to="{name:'index'}">index </router-link>
<router-link to="/detail">去详情 </router-link>


<button @click="todetail"> q去详情页</button>
<button @click="toMine"> 个人中心页</button>
<!-- 预留展示区域 -->
<router-view></router-view>
    </div>

    <template id="index">
        <div>
            首页


            <router-link to="/detail">去详情 </router-link>
            <router-link to="/detail?id=104&name='zs'">去详情2222 </router-link>
            <router-link :to="{path:'/detail',query:{id:103,name:'zs'}}">去详情 </router-link>


            <router-link :to="{name:'my',params:{userid:234}}"> 去个人中心 </router-link>
            <!-- 错误写法 -->
            <router-link :to="{name:'my'}"> 去个人中心 </router-link>

        </div>
    </template>

    <template id="detail">
        <div>
            详情页
            <router-link to="/detail/play"> play</router-link>

            <router-view></router-view>

        </div>
    </template>

    <template id="course">
        <div>
            课程信息缓冲

           
        </div>
    </template>
    <template id="play">
        <div>
            课程信息播放
        </div>
    </template>

    <template id="mine">
        <div>
            个人页
        </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. 创建路由实例对象
         const router = new VueRouter({
            // 3.创建映射关系
            routes:[
                // 路由重定向
                {
                    path:'/',
                    redirect:'/index'
                },
                {
                    path:'/index',
                    component: index,
                    name:'index'
                    
                },
                {
                    path:'/detail',
                    component: detail,
                    // 路由嵌套
                    children:[
                        {
                            path:"/play",
                            component:play

                        },
                        {
                            path:"course",
                            component:course
                        },
                    ]
                },
                // 路径传参
                {
                    path:'/mine/:userid',
                    component:mine,
                    name:'my'
                }
            ],
            // 自定义路由高亮
            linkActiveClass:"myactive"
        });

    const vm = new Vue({
        // 4.将路由挂载在vue上
        // router:router,
        router,
        el: '#app',
        data: {
        },
        methods: {
            // 函数式跳转
            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.路由高亮

选中路由高亮

  1. 使用默认的样式直接设置router-link-active
  2. 自定义样式配置 linkActiveClass:'自定义的类名'

 39.路由重定向

redirect可以进行路由的重定向

                 // 路由重定向
                {
                    path:'/',
                    redirect:'/index'
                },
     

40.ref的使用 

获取dom节点

  1. dom节点记上ref属性,可以理解为给dom节点起了个名字。
  2. 加上ref之后,在$refs属性中多了这个元素的引用。
  3. 通过vue实例的$refs属性拿到这个dom元素。

获取组件

  1. 给组件记上ref属性,可以理解为给组件起了个名字。
  2. 加上ref之后,在$refs属性中多了这个组件的引用。
  3. 通过vue实例的$refs属性拿到这个组件的引用,之后可以通过这个引用调用子组件的方法,或者获取子组件的数据。

 41.属性计算,属性监听

 Watch用法

监听data中属性的改变:
<div id="app">
  <input type="text" v-model="firstName"> +
  <input type="text" v-model="lastName"> =
  <span>{{fullName}}</span>
</div>

<script>
  // 创建 Vue 实例,得到 ViewModel
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'jack',
      lastName: 'chen',
      fullName: 'jack - chen'
    },
    methods: {},
    watch: {
      'firstName': function (newVal, oldVal) { // 第一个参数是新数据,第二个参数是旧数据
        this.fullName = newVal + ' - ' + this.lastName;
      },
      'lastName': function (newVal, oldVal) {
        this.fullName = this.firstName + ' - ' + newVal;
      }
    }
  });
</script>

监听路由对象的改变:
<div id="app">
  <router-link to="/login">登录</router-link>
  <router-link to="/register">注册</router-link>

  <router-view></router-view>
</div>
<script>
  var login = Vue.extend({
    template: '<h1>登录组件</h1>'
  });

  var register = Vue.extend({
    template: '<h1>注册组件</h1>'
  });

  var router = new VueRouter({
    routes: [
      { path: "/login", component: login },
      { path: "/register", component: register }
    ]
  });

  // 创建 Vue 实例,得到 ViewModel
  var vm = new Vue({
    el: '#app',
    data: {},
    methods: {},
    router: router,
    watch: {
      '$route': function (newVal, oldVal) {
        if (newVal.path === '/login') {
          console.log('这是登录组件');
        }
      }
    }
  });
</script>

Computed用法

默认只有getter的计算属性:
<div id="app">
  <input type="text" v-model="firstName"> +
  <input type="text" v-model="lastName"> =
  <span>{{fullName}}</span>
</div>

<script>
  // 创建 Vue 实例,得到 ViewModel
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'jack',
      lastName: 'chen'
    },
    methods: {},
    computed: { // 计算属性; 特点:当计算属性中所以来的任何一个 data 属性改变之后,都会重新触发 本计算属性 的重新计算,从而更新 fullName 的值
      fullName() {
        return this.firstName + ' - ' + this.lastName;
      }
    }
  });
</script>

定义有getter和setter的计算属性:
<div id="app">
  <input type="text" v-model="firstName">
  <input type="text" v-model="lastName">
  <!-- 点击按钮重新为 计算属性 fullName 赋值 -->
  <input type="button" value="修改fullName" @click="changeName">

  <span>{{fullName}}</span>
</div>

<script>
  // 创建 Vue 实例,得到 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>

 method、computed和watch的区别

  1. computed属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。主要当作属性来使用,使用的时候不加();
  2. methods方法表示一个具体的操作,主要书写业务逻辑;
  3. watch一个对象,键是需要观察的表达式,值是对应回调函数。主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作;可以看作是computedmethods的结合体
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值