VUE简单入门

Vue 基础

简介

  1. Javascript框架
  2. 简化Dom操作
  3. 响应式数据驱动

第一个Vue程序

  1. 导入开发版本的Vue.js
  2. 创建Vue实例对象,设置el属性和data属性
  3. 使用 简洁 的 模板语法 把数据渲染到页面上
<body>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
<div id="app">
    {{message}}
</div>
<script>
    var app =new Vue({
        el:"#app",
        data:{
            message:"你好,小洛"
        }
    })
</script>
</body>

el挂载点

  • el是用来设置Vue实例挂载(管理) 的元素

  • Vue 实例的作用范围是什么呢?
    Vue会管理el选项命中的元素及其内部的后代元素

  • 是否可以使用其他的选择器?
    可以使用其他的选择器,但是建议使用ID选择器

  • 是否可以设置其他的dom元素呢?
    可以使用其他的双标签,不能使用HTML和BODY

<body id="body">
    {{message}}
    <h2 id="app" class="app">
        {{message}}
        <span>{{message}}
        </span>
    </h2>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
    var app=new Vue({
        //  el:"#app",
        // el:".app",
        el:"div",
        // el:"#body",
        data:{
            message:"广海啊"
        }
    })
</script>
</body>

data数据对象

  1. Vue中用到的数据定义 在 data中
  2. data 中可以写 复杂类型的数据
  3. 渲染复杂类型数据时,遵守js的语法即可
<body>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
    {{message}}
    <h2>{{school.name}}     {{school.mobile}}</h2>
    <ul>
        <li>{{campus[2]}}</li>
        <li>{{campus[1]}}</li>
    </ul>
</div>
    
<script>
    var app=new Vue({
        el:"#app",
        data:{
            message:"你好,小骆",
            school:{
                name:"程序员",
                mobile:"20931290312"
            },
            campus:["上海","北京","广州","深圳"]
        }
    })
</script>
</body>

本地应用

v-text

  1. v-text 指令的作用是:设置标签的内容(context)
  2. 默认写法会替换全部内容,使用差值表达式 {{}} 可以替换指定内容
  3. 内部支持写表达式
<body>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <div id="app">
        <h2 v-text="message">广州</h2>
        <h2 v-text="info+'!'">广州</h2>
        <h2>{{message+'!'}} 广州</h2>
    </div>

    <script>
        var app=new Vue({
            el:"#app",
            data:{
                message:"程序!!!猿",
                info:"想进大厂打杂"
            }
        })
    </script>
    
</body>

v-html

  1. v-html指令的作用是: 设置元素的innerHTML
  2. 内容中有html结构会被解析为标签
  3. v-text指令无论内容是什么,只会解析为文本
  4. 解析文本使用v-text ,需要解析html结构使用v-html
<body>
    <div id="app">
        <p v-html="content"></p>
        <p v-text="content"></p>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app=new Vue({
            el:"#app",
            data:{
                content:"<a href='http://www.baidu.com'>百度</a>"
            }
        })
    </script>
    
</body>

v-on

  1. v-on指令的作用是: 为元素绑定事件
  2. 事件名不需要写on
  3. 指令可以简写为 @
  4. 绑定的方法应以在methods属性中
  5. 方法内部通过this关键字 可以 访问定义在data 中数据
<body>
    <div id="app">
        <input type="button" value="v-on指令" v-on:click="doIt">
        <input type="button" value="v-on简写" @click="doIt">
        <input type="button" value="双击事件" @dblclick="doIt">
        <h2 @click="changeFood">{{food}}</h2>
    </div>
    <!-- 1.开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                food:"番茄炒蛋",
                id:1
            },
            methods: {
                doIt:function(){
                    alert("做It");         
                },
                changeFood:function(){
                    //console.log(this.food);
                    this.food+="好吃!"
                }
            },
        })
    </script>
</body>

计数器

  1. data中定义数据:比如 num
  2. methods中添加两个方法,比如add,sub
  3. 使用v-text 将 num 设置给 span 标签
  4. 使用 v-on将 add,sub 分别绑定给 + ,- 按钮
  5. 累加的逻辑: 小于10 累加, 否则提示
  6. 递减的逻辑: 大于10 递减, 否则提示

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <div id="app">
        <!-- 计数器 -->
        <div class="input-num">
          <button @click="sub">
            -
          </button>
          <span>{{ num }}</span>
          <button @click="add">
            +
          </button>
        </div>
        <img
        src="http://www.itheima.com/images/logo.png"
        alt=""
      />
      </div>
    </body>
  </html>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- 编码 -->
  <script>
    // 创建Vue实例
    var app = new Vue({
      el: "#app",
      data: {
        num: 1,
        min: 0,
        max: 10
      },
      methods: {
        sub() {
          if (this.num > this.min) {
            this.num--;
          } else {
            alert("别点啦,到底啦");
          }
        },
        add() {
          if (this.num < this.max) {
            this.num++;
          } else {
            alert("别点啦,到头啦");
          }
        }
      }
    });
  </script>
  

index.css


body{
  background-color: #f5f5f5;
}
#app {
  width: 480px;
  height: 80px;
  margin: 200px auto;
}
.input-num {
  margin-top:20px;
  height: 100%;
  display: flex;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 4px 4px 4px #adadad;
  border: 1px solid #c7c7c7;
  background-color: #c7c7c7;
}
.input-num button {
  width: 150px;
  height: 100%;
  font-size: 40px;
  color: #ad2a27;
  cursor: pointer;
  border: none;
  outline: none;
  background-color:rgba(0, 0, 0, 0);
}
.input-num span {
  height: 100%;
  font-size: 40px;
  flex: 1;
  text-align: center;
  line-height: 80px;
  font-family:auto;
  background-color: white;
}
img{
  float: right;
  margin-top: 50px;
}

v-show

  1. v-show指令的作用是 根据真假切换元素的显示状态
  2. 原理是修改元素的display,实现显示隐藏
  3. 指令后面的内容,最终都会解析为布尔值
  4. 值为true元素显示,值为false 元素隐藏
  5. 数据改变之后,对应元素的显示状态会同步更新
<body>
    <!-- 1.开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <div id="app">
        <input type="button" value="切换状态" @click="changeIsShow">
        <input type="button" value="累加年龄" @click="addAge">
        <img v-show="isShow" src="./img/图片1.gif" alt="">
        <img v-show="age>=18" src="./img/图片1.gif" alt="">
    </div>

    <script>
        var app=new Vue({
            el:"#app",
            data:{
                isShow:false,
                age:14
            },
            methods:{
                changeIsShow:function(){
                    this.isShow=!this.isShow;
                },
                addAge:function(){
                    this.age++;
                }
            },
        })
    </script>
    
</body>

v-if

  1. v-if 指令的作用是 : 根据表达式的真假切换元素的显示状态
  2. 本质是通过操纵dom元素来切换显示状态
  3. 表达式的值为true 元素 存在于dom树中,为 false,从dom树中移除
  4. 频繁的切换v-show ,反之使用 v-if ,前者的切换消耗小
<body>
    <div id="app">
        <input type="button" value="切换显示" @click="toggleIsShow">
        <p v-if="isShow">程序员</p>
        <p v-show="isShow">程序员 - v-show修饰</p>
        <h2 v-if="temperature>=35">热死啦</h2>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                isShow:false,
                temperature:36
            },
            methods: {
                toggleIsShow:function(){
                    this.isShow = !this.isShow;
                }
            },
        })
    </script>
</body>

v-bind

  1. v-bind 指令的作用是:为元素绑定属性
  2. 完整写法是 v-bind:属性名
  3. 简写的话可以直接省略 v-bind ,只保留 : 属性名
  4. 需要动态的增删 class 建议 使用对象的方式
<body>
    <div id="app">
        <img v-bind:src="imgSrc" alt="">
        <br>
        <img :src="imgSrc" alt="" :title="imgTitle+'!!!'" :class="isActive?'active':''" @click="toggleActive">
        <br>
        <img :src="imgSrc" alt="" :title="imgTitle+'!!!'" :class="{active:isActive}" @click="toggleActive">
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                imgSrc:"http://www.itheima.com/images/logo.png",
                imgTitle:"程序员",
                isActive:false
            },
            methods: {
                toggleActive:function(){
                    this.isActive = !this.isActive;
                }
            },
        })
    </script>
</body>

图片切换

  1. 定义图片数组
  2. 添加图片索引
  3. 绑定src属性
  4. 图片切换逻辑
  5. 显示状态切换
<body>
  <div id="mask">
    <div class="center">
      <h2 class="title">
        <img src="./images/logo.png" alt="">
        广州校区
      </h2>
      <!-- 图片 -->
      <img :src="imgArr[index]" alt="" />
      <!-- 左箭头 -->
      <!-- <a href="javascript:void(0)" v-show="index!=0" @click="prev" class="left">
        <img src="./images/prev.png" alt="" />
      </a> -->
      <a href="javascript:void(0)" v-if="index!=0" @click="prev" class="left">
          <img src="./images/prev.png" alt="" />
        </a>
      <!-- 右箭头 -->
      <a href="javascript:void(0)" v-show="index<imgArr.length-1" @click="next" class="right">
        <img src="./images/next.png" alt="" />
      </a>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

  <script>
    var app = new Vue({
      el: "#mask",
      data: {
        imgArr: [
          "./images/00.jpg",
          "./images/01.jpg",
          "./images/02.jpg",
          "./images/03.jpg",
          "./images/04.jpg",
          "./images/05.jpg",
          "./images/06.jpg",
          "./images/07.jpg",
          "./images/08.jpg",
          "./images/09.jpg",
          "./images/10.jpg",
        ],
        index: 0
      },
      methods: {
        prev:function(){
          this.index--;
        },
        next:function(){
          this.index++;
        }
      },
    })
  </script>
</body>

为什么要使用href=”javascript:void(0);”
javascript:是伪协议,表示url的内容通过javascript执行。void(0)表示不作任何操作,这样会防止链接跳转到其他页面。这么做往往是为了保留链接的样式,但不让链接执行实际操作,

<a href="javascript:void(0)" onClick="window.open()">
 点击链接后,页面不动,只打开链接

<a href="#" οnclick="javascript:return false;"> 
作用一样,但不同浏览器会有差异。
  • 列表数据使用 数组 保存
  • v-bind 指令 可以 设置元素 属性 比如,src
  • v-show 和 v-if 都可以切换元素的显示状态,频繁切换用 v-show

v-for

  • v-for 指令的作用是:根据数据生成列表结构
  • 数组经常和v-for结合使用
  • 语法是 (item,index) in 数据
  • item 和 index 可以结合其他指令一起使用
  • 数组长度的更新会同步到页面上,是响应式的
<body>
    <div id="app">
        <input type="button" value="添加数据" @click="add">
        <input type="button" value="移除数据" @click="remove">

        <ul>
            <li v-for="(it,index) in arr">
                {{ index+1 }}黑马程序员校区:{{ it }}
            </li>
        </ul>
        <h2 v-for="item in vegetables" v-bind:title="item.name">
            {{ item.name }}
        </h2>
    </div>
    <!-- 1.开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                arr:["北京","上海","广州","深圳"],
                vegetables:[
                    {name:"西兰花炒蛋"},
                    {name:"蛋炒西蓝花"}
                ]
            },
            methods: {
                add:function(){
                    this.vegetables.push({ name:"花菜炒蛋" });
                },
                remove:function(){
                    this.vegetables.shift();
                }
            },
        })
    </script>
</body>

v-on补充

  • 事件绑定的方法写成函数调用的形式,可以传入自定义参数
  • 定义方式时需要定义形参来接收传入的实参
  • 事件的后面 跟上 . 修饰符 可以对事件进行限制
  • .enter 可以限制触发的按键为回车
  • 事件修饰符有多种
<body>
    <div id="app">
        <input type="button" value="点击" @click="doIt(666,'老铁')">
        <input type="text" @keyup.enter="sayHi">
    </div>
    <!-- 1.开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            methods: {
                doIt:function(p1,p2){
                    console.log("做it");
                    console.log(p1);
                    console.log(p2);
                },
                sayHi:function(){
                    alert("吃了没");
                }
            },
        })
    </script>
</body>

v-model

  • 获取和设置表单元素的值(双向数据绑定)
  • v-model 指令的作用时便捷的设置和获取表单元素的值
  • 绑定的数据会和表单元素值相关联
  • 绑定的数据<- -> 表单元素的值
<body>
    <div id="app">
        <input type="button" value="修改message" @click="setM">
        <input type="text" v-model="message" @keyup.enter="getM">
        <h2>{{ message }}</h2>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                message:"黑马程序员"
            },
            methods: {
                getM:function(){
                    alert(this.message);
                },
                setM:function(){
                    this.message ="酷丁鱼";
                }
            },
        })
    </script>
</body>

记事本

新增

  1. 生成列表结构 (v-for)
  2. 获取用户输入 (v-model)
  3. 回车,新增数据 (v-on .enter 添加数据)

删除

  • 点击删除指定内容(v-on splice 索引)
  1. 数据改变,和 数据绑定的元素同步改变
  2. 事件的自定义参数
  3. splice方法的作用

统计

  • 统计信息个数 (v-text length)
  1. 基于数据的开发方式
  2. v-text 指令的作用

清空

  • 点击清楚所有信息 (v-on 清空数组)
  1. 基于数据的开发方式

隐藏

  • 没有数据时,隐藏元素(v-show , v-if 数组非空)

总结

  1. 列表结构可以通过 v-for 指令结合数据生成
  2. v-on 结合 事件修饰符 可以 对 事件进行限制, 比如 .enter
  3. v-on 在绑定 事件时 可以传递自定义参数
  4. 通过 v-model 可以 快速的设置 和获取表单元素的值
  5. 基于数据的开发方式
<body>
  <!-- 主体区域 -->
  <section id="todoapp">
    <!-- 输入框 -->
    <header class="header">
      <h1>记事本</h1>
      <input v-model="inputValue" @keyup.enter="add" autofocus="autofocus" autocomplete="off" placeholder="请输入任务"
        class="new-todo" />
    </header>
    <!-- 列表区域 -->
    <section class="main">
      <ul class="todo-list">
        <li class="todo" v-for="(item,index) in list">
          <div class="view">
            <span class="index">{{ index+1 }}.</span>
            <label>{{ item }}</label>
            <button class="destroy" @click="remove(index)"></button>
          </div>
        </li>
      </ul>
    </section>
    <!-- 统计和清空 -->
    <footer class="footer" v-show="list.length!=0">
      <span class="todo-count" v-if="list.length!=0">
        <strong>{{ list.length }}</strong> items left
      </span>
      <button v-show="list.length!=0" class="clear-completed" @click="clear">
        Clear
      </button>
    </footer>
  </section>
  <!-- 底部 -->
  <footer class="info">
    <p>
      <a href="http://www.itheima.com/"><img src="./img/black.png" alt="" /></a>
    </p>
  </footer>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    var app = new Vue({
      el: "#todoapp",
      data: {
        list: ["写代码", "吃饭饭", "睡觉觉"],
        inputValue: "好好学习,天天向上"
      },
      methods: {
        add: function () {
          this.list.push(this.inputValue);
        },
        remove: function (index) {
          console.log("删除");
          console.log(index);
          this.list.splice(index, 1);
        },
        clear: function () {
          this.list = [];
        }
      },
    })
  </script>
</body>

网络应用

axios

  • 功能强大的网络请求库
    在这里插入图片描述
<body>
    <input type="button" value="get请求" class="get">
    <input type="button" value="post请求" class="post">
    <!-- 官网提供的 axios 在线地址 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        /*
            接口1:随机笑话
            请求地址:https://autumnfish.cn/api/joke/list
            请求方法:get
            请求参数:num(笑话条数,数字)
            响应内容:随机笑话
        */
        document.querySelector(".get").onclick = function () {
            axios.get("https://autumnfish.cn/api/joke/list?num=6")
            // axios.get("https://autumnfish.cn/api/joke/list1234?num=6")
            .then(function (response) {
                console.log(response);
              },function(err){
                  console.log(err);
              })
        }
        /*
             接口2:用户注册
             请求地址:https://autumnfish.cn/api/user/reg
             请求方法:post
             请求参数:username(用户名,字符串)
             响应内容:注册成功或失败
         */
        document.querySelector(".post").onclick = function () {
            axios.post("https://autumnfish.cn/api/user/reg",{username:"盐焗西兰花"})
            .then(function(response){
                console.log(response);
                console.log(this.skill);
            },function (err) {
                console.log(err);
              })
          }

    </script>
</body>
  1. axios必须先导入才可以使用
  2. 使用get或post方法即可发送对应的请求
  3. then方法中的回调函数会在请求成功或失败时触发
  4. 通过回调函数的形参可以获取响应内容,或 错误信息

axios+vue


<body>
    <div id="app">
        <input type="button" value="获取笑话" @click="getJoke">
        <p> {{ joke }}</p>
    </div>
    <!-- 官网提供的 axios 在线地址 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        /*
            接口:随机获取一条笑话
            请求地址:https://autumnfish.cn/api/joke
            请求方法:get
            请求参数:无
            响应内容:随机笑话
        */
        var app = new Vue({
            el:"#app",
            data:{
                joke:"很好笑的笑话"
            },
            methods: {
                getJoke:function(){
                    // console.log(this.joke);
                    var that = this;
                    axios.get("https://autumnfish.cn/api/joke").then(function(response){
                        // console.log(response)
                        console.log(response.data);
                        // console.log(this.joke);
                        that.joke = response.data;
                    },function (err) {  })
                }
            },
        })

    </script>
</body>
  • axios 回调函数中 this 已经改变, 无法访问到data 中数据
  • 把 this 保存起来 , 回调 函数 中 直接 使用保存 的 this 即可
  • 和 本地应用的 最大 区别就是改变了 数据来源

天知道

回车查询

  1. 按下回车(v-on .enter)
  2. 查询数据(axios 接口 v-model)
  3. 渲染数据(v-for 数组 that)

在这里插入图片描述

  • 应用的逻辑代码建议和页面分离,使用单独的js文件编写
  • axios回调 函数 中 this 指向 改变了 , 需要额外的保存一份
  • 服务器返回的数据比较复杂时,获取的时候需要注意层级结构

点击查询

  1. 点击城市(v-on 自定义参数)
  2. 查询数据 (this. 方法())
  3. 渲染数据
  • 自定义参数可以让代码的复用性更高
  • methods中定义的方法内部,可以通过 this 关键字 点出 其他的方法

<body>
  <div class="wrap" id="app">
    <div class="search_form">
      <div class="logo"><img src="img/logo.png" alt="logo" /></div>
      <div class="form_group">
        <input type="text" class="input_txt" placeholder="请输入查询的天气" v-model="city" @keyup.enter="queryWeather" />
        <button class="input_sub" @click="queryWeather">
          搜 索
        </button>
      </div>
      <div class="hotkey">
        <!-- <a href="javascript:;" @click="clickSearch('北京')">北京</a>
          <a href="javascript:;" @click="clickSearch('上海')">上海</a>
          <a href="javascript:;" @click="clickSearch('广州')">广州</a>
          <a href="javascript:;" @click="clickSearch('深圳')">深圳</a> -->
        <a href="javascript:;" v-for="city in hotCitys" @click="clickSearch(city)">{{ city }}</a>
      </div>
    </div>
    <ul class="weather_list">
      <li v-for="(item,index) in forecastList" :key="item.date" :style="{transitionDelay:index*100+'ms'}">
        <div class="info_type">
          <span class="iconfont">{{ item.type }}</span>
        </div>
        <div class="info_temp">
          <b>{{ item.low}}</b>
          ~
          <b>{{ item.high}}</b>

        </div>
        <div class="info_date">
          <span>{{ item.date }}</span>
        </div>
      </li>
    </ul>
  </div>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- 官网提供的 axios 在线地址 -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    new Vue({
      el: "#app",
      data: {
        city: "武汉",
        forecastList: [],
        hotCitys: ["北京", "上海", "广州", "深圳"]
      },
      methods: {
        queryWeather() {
          this.forecastList = [];
          axios
            .get(`http://wthrcdn.etouch.cn/weather_mini?city=${this.city}`)
            .then(res => {
              console.log(res);
              this.forecastList = res.data.data.forecast;
            })
            .catch(err => {
              console.log(err);
            })
            .finally(() => { });
        },
        clickSearch(city) {
          this.city = city;
          this.queryWeather();
        }
      }
    });
  </script>
</body>

js:

/*
  请求地址:http://wthrcdn.etouch.cn/weather_mini
  请求方法:get
  请求参数:city(城市名)
  响应内容:天气信息

  1. 点击回车
  2. 查询数据
  3. 渲染数据
  */
 var app = new Vue({
     el:"#app",
     data:{
         city:'',
         weatherList:[]
     },
     methods: {
         searchWeather:function(){
            //  console.log('天气查询');
            //  console.log(this.city);
            // 调用接口
            // 保存this
            var that = this;
            axios.get('http://wthrcdn.etouch.cn/weather_mini?city='+this.city)
            .then(function(response){
                // console.log(response);
                console.log(response.data.data.forecast);
                that.weatherList = response.data.data.forecast
            })
            .catch(function(err){})
         }
     },
 })

综合应用

歌曲搜索

  1. 按下回车(v-on .enter)
  2. 查询数据 (axios 接口 v-model)
  3. 渲染数据 (v-for 数组 that)
  • 服务器返回的数据比较复杂时,获取的时候需要注意层级结构
  • 通过审查元素快速定位到需要操作的元素

歌曲播放

  1. 点击播放 (v-on 自定义参数)
  2. 歌曲地址获取 (接口 歌曲id)
  3. 歌曲地址设置 (v-bind)
  • 歌曲id 依赖 歌曲搜索的结果 , 对于不用的数据也需要关注

歌曲封面

  1. 点击播放 (增加逻辑)
  2. 歌曲封面获取 (接口 歌曲 id)
  3. 歌曲封面设置 (v-bind)
  • 在vue 中 通过 v-bind 操纵属性
  • 本地无法获取的数据,基本都会有对应的接口

歌曲评论

  1. 点击播放(增加逻辑)
  2. 歌曲评论获取 (接口 歌曲id)
  3. 歌曲评论渲染(v-for)
  • 在vue中通过v-for 生成列表

播放动画

  1. 监听音乐播放(v-on play)
  2. 监听音乐暂停(v-on pause)
  3. 操作类名 (v-bind 对象)
  • audio 标签 的 play 事件 会在音频播放的时候触发
  • audio 标签 的 pause 事件 会在音频暂停的时候触发
  • 通过对象 的 方式设置类名,类名生效与 否取决于 后面的值 的真假

mv播放

  1. mv图标显示(v-if)
  2. mv地址获取(接口 mvid)
  3. 遮罩层 (v-show v-on)
  4. mv地址设置 (v-bind)
<body>
  <div class="wrap">
    <div class="play_wrap" id="player">
      <div class="search_bar">
        <img src="images/player_title.png" alt="" />
        <!-- 搜索歌曲 -->
        <input type="text" autocomplete="off" v-model='query' @keyup.enter="searchMusic();" />
      </div>
      <div class="center_con">
        <!-- 搜索歌曲列表 -->
        <div class='song_wrapper' ref='song_wrapper'>
          <ul class="song_list">
            <li v-for="item in musicList">
              <!-- 点击放歌 -->
              <a href="javascript:;" @click='playMusic(item.id)'></a>
              <b>{{item.name}}</b>
              <span>
                <i @click="playMv(item.mvid)" v-if="item.mvid!=0"></i>
              </span>
            </li>

          </ul>
          <img src="images/line.png" class="switch_btn" alt="">
        </div>
        <!-- 歌曲信息容器 -->
        <div class="player_con" :class="{playing:isPlay}">
          <img src="images/player_bar.png" class="play_bar" />
          <!-- 黑胶碟片 -->
          <img src="images/disc.png" class="disc autoRotate" />
          <img :src="coverUrl==''?'./images/cover.png':coverUrl" class="cover autoRotate" />
        </div>
        <!-- 评论容器 -->
        <div class="comment_wrapper" ref='comment_wrapper'>
          <h5 class='title'>热门留言</h5>
          <div class='comment_list'>

            <dl v-for="item in hotComments">
              <dt>
                <img :src="item.user.avatarUrl" alt="" />
              </dt>
              <dd class="name">{{item.user.nickname}}</dd>
              <dd class="detail">
                {{item.content}}
              </dd>
            </dl>
          </div>
          <img src="images/line.png" class="right_line">
        </div>
      </div>
      <div class="audio_con">
        <audio ref='audio' @play="play" @pause="pause" :src="musicUrl" controls autoplay loop class="myaudio"></audio>
      </div>
      <div class="video_con" v-show="showVideo">
        <video ref='video' :src="mvUrl" controls="controls"></video>
        <div class="mask" @click="closeMv"></div>
      </div>
    </div>
  </div>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- 官网提供的 axios 在线地址 -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script type="text/javascript">
    // 设置axios的基地址
    axios.defaults.baseURL = 'https://autumnfish.cn';
    // axios.defaults.baseURL = 'http://localhost:3000';



    // 实例化vue
    var app = new Vue({
      el: "#player",
      data: {
        // 搜索关键字
        query: '',
        // 歌曲列表
        musicList: [],
        // 歌曲url
        musicUrl: '',
        // 是否正在播放
        isPlay: false,
        // 歌曲热门评论
        hotComments: [],
        // 歌曲封面地址
        coverUrl: '',
        // 显示视频播放
        showVideo: false,
        // mv地址
        mvUrl: ''
      },
      // 方法
      methods: {
        // 搜索歌曲
        searchMusic() {
          if (this.query == 0) {
            return
          }
          axios.get('/search?keywords=' + this.query).then(response => {
            // 保存内容
            this.musicList = response.data.result.songs;

          })

          // 清空搜索
          this.query = ''
        },
        // 播放歌曲
        playMusic(musicId) {
          // 获取歌曲url
          axios.get('/song/url?id=' + musicId).then(response => {
            // 保存歌曲url地址
            this.musicUrl = response.data.data[0].url
          })
          // 获取歌曲热门评论
          axios.get('/comment/hot?type=0&id=' + musicId).then(response => {
            // console.log(response)
            // 保存热门评论
            this.hotComments = response.data.hotComments

          })
          // 获取歌曲封面
          axios.get('/song/detail?ids=' + musicId).then(response => {
            // console.log(response)
            // 设置封面
            this.coverUrl = response.data.songs[0].al.picUrl
          })

        },
        // audio的play事件
        play() {
          this.isPlay = true
          // 清空mv的信息
          this.mvUrl = ''
        },
        // audio的pause事件
        pause() {
          this.isPlay = false
        },
        // 播放mv
        playMv(vid) {
          if (vid) {
            this.showVideo = true;
            // 获取mv信息
            axios.get('/mv/url?id=' + vid).then(response => {
              // console.log(response)
              // 暂停歌曲播放
              this.$refs.audio.pause()
              // 获取mv地址
              this.mvUrl = response.data.data.url
            })
          }
        },
        // 关闭mv界面
        closeMv() {
          this.showVideo = false
          this.$refs.video.pause()
        },
        // 搜索历史记录中的歌曲
        historySearch(history) {
          this.query = history
          this.searchMusic()
          this.showHistory = false;
        }
      },

    })

  </script>
</body>
/*
  1:歌曲搜索接口
    请求地址:https://autumnfish.cn/search
    请求方法:get
    请求参数:keywords(查询关键字)
    响应内容:歌曲搜索结果

  2:歌曲url获取接口
    请求地址:https://autumnfish.cn/song/url
    请求方法:get
    请求参数:id(歌曲id)
    响应内容:歌曲url地址
  3.歌曲详情获取
    请求地址:https://autumnfish.cn/song/detail
    请求方法:get
    请求参数:ids(歌曲id)
    响应内容:歌曲详情(包括封面信息)
  4.热门评论获取
    请求地址:https://autumnfish.cn/comment/hot?type=0
    请求方法:get
    请求参数:id(歌曲id,地址中的type固定为0)
    响应内容:歌曲的热门评论
  5.mv地址获取
    请求地址:https://autumnfish.cn/mv/url
    请求方法:get
    请求参数:id(mvid,为0表示没有mv)
    响应内容:mv的地址
*/
var app = new Vue({
  el: "#player",
  data: {
    // 查询关键字
    query: "",
    // 歌曲数组
    musicList: [],
    // 歌曲地址
    musicUrl: "",
    // 歌曲封面
    musicCover: "",
    // 歌曲评论
    hotComments: [],
    // 动画播放状态
    isPlaying: false,
    // 遮罩层的显示状态
    isShow: false,
    // mv地址
    mvUrl: ""
  },
  methods: {
    // 歌曲搜索
    searchMusic: function() {
      var that = this;
      axios.get("https://music.cyrilstudio.top/search?keywords=" + this.query).then(
        function(response) {
          // console.log(response);
          that.musicList = response.data.result.songs;
          console.log(response.data.result.songs);
        },
        function(err) {}
      );
    },
    // 歌曲播放
    playMusic: function(musicId) {
      //   console.log(musicId);
      var that = this;
      // 获取歌曲地址
      axios.get("https://api.imjad.cn/cloudmusic/?type=detail&id=" + musicId).then(
        function(response) {
          // console.log(response);
          // console.log(response.data.data[0].url);
          that.musicUrl = response.data.data[0].url;
        },
        function(err) {}
      );

      // 歌曲详情获取
      axios.get("https://autumnfish.cn/song/detail?ids=" + musicId).then(
        function(response) {
          // console.log(response);
          // console.log(response.data.songs[0].al.picUrl);
          that.musicCover = response.data.songs[0].al.picUrl;
        },
        function(err) {}
      );

      // 歌曲评论获取
      axios.get("https://autumnfish.cn/comment/hot?type=0&id=" + musicId).then(
        function(response) {
          // console.log(response);
          // console.log(response.data.hotComments);
          that.hotComments = response.data.hotComments;
        },
        function(err) {}
      );
    },
    // 歌曲播放
    play: function() {
      // console.log("play");
      this.isPlaying = true;
    },
    // 歌曲暂停
    pause: function() {
      // console.log("pause");
      this.isPlaying = false;
    },
    // 播放mv
    playMV: function(mvid) {
      var that = this;
      document.querySelector('#audio').pause();
      that.isPlaying = false;
      
      axios.get("https://autumnfish.cn/mv/url?id=" + mvid).then(
        function(response) {
          // console.log(response);
          console.log(response.data.data.url);
          that.isShow = true;
          that.mvUrl = response.data.data.url;
        },
        function(err) {}
      );
    },
    // 隐藏
    hide: function() {
      document.querySelector('#video').pause();
      this.isShow = false;
    }
  }
});

总结

  • 不同的接口需要的数据 是 不同 的,文档的阅读需要仔细
  • 页面结构复杂之后,通过审查元素的方法 去快速定位相关元素
  • 响应式 的 数据 都需要 定义 在 data 中定义

在通过观看黑马的这个vue入门教程,做到后面发现,两个小练习的一些接口,已经无法使用了,就是功能实现不了,按照源码去敲的话, 然后去操作之后
控制台,会显示报错,什么GET xxx 我大概的看法就是说,无法获取,得到数据了。 百度过后,也没有解决问题。
回头一想,我们学一个东西,并不能说刻板的完全去复制粘贴一个一摸一样的 成果。我们学习,是通过理解,通过模仿,一步一步的掌握一个东西,那么在这里的话,我觉得 我们需要着重的去看的内容是, 老师课堂上写的一些逻辑。 (如何实现该功能)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值