Vue快速入门

85 阅读6分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情

vue学习官网 导入开发包(在联网环境下):

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

vue基础

设置el挂载点

<body>
    {{message}}
    <h2 id="app" class="app">
        {{message}}
        <span>{{message}}</span>
    </h2>
    <script>
        var app=new Vue({
            //el:'#app',
            el:'.app',
            data:{
                message:'黑马程序员'
            }
        })
    </script>
    
</body>

知识点:

  • vue实例作用范围:el选项命中的选项及其内部的后代元素
  • 可以使用其它选择器,但是建议使用id选择器
  • 可以设置其它的dom元素,也可以使用其它的双标签,但不能使用HTML和body

data数据对象

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

知识点:

  • Vue中用到的数据定义在data中
  • data中可以写复杂类型的数据
  • 渲染复杂类型数据时,遵守js的语法即可

本地应用

v-text指令

<body>
    <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-text指令的作用是:设置标签的内容(textContent)
  • 默认写法会替换全部内容,使用差值表达式{{}}可以替换指定内容

v-html指令

<body>
    <div id="app">
        <p v-html="content"></p>
        <p v-text="content"></p>
    </div>
    <script>
        var app=new Vue({
            el:'#app',
            data:{
                content:"<a href='http://www.itheima.com'>黑马程序员</a>"
            }
        })
    </script>
</body>

知识点:

  • v-html指令的作用是:设置元素的innerHTML
  • 内容中有html结构会被解析为标签
  • v-text指令无论内容是什么,只会解析为文本
  • 解析文本使用v-text,需要解析html结构使用v-html

v-on指令

<body>
    <div id="app">
        <input type="button" value="点击" @click="doIt(666,'老大')">
        <input type="text" @keyup.enter="sayHi">
    </div>
    <script>
        var app =new Vue({
            el:'#app',
            methods:{
                doIt:function(p1,p2){
                    console.log("hello");   
                    console.log(p1);
                    console.log(p2);
                },
                sayHi:function(){
                    alert("吃了没")
                }
            }
        })
    </script>
</body>

知识点:

  • 事件绑定的方法写成函数调用的形式,可以传入自定义参数
  • 定义方法时需要定义形参来接收传入的实参
  • 事件的后面跟上 .修饰符 可以对事件进行限制
  • .enter 可以限制触发的按键为回车
  • 事件修饰符有两种

计数器

<body>
    <div id="app">
        <div class="input-num">
            <button @click="sub">-</button>
            <span>{{ num }}</span>
            <button @click="add">+</button>
        </div>
    </div>
</body>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            num: 1
        },
        methods: {
            sub: function () { 
                if(this.num>0){
                    this.num--
                }else{
                    alert("到点了")
                }
            },
            add: function () { 
                if(this.num<10){
                    this.num++
                }else{
                    alert("限购10件")
                }
            }
        }
    })
</script>

知识点:

  • 创建vue示例时:el(挂载点),data(数据),methods(方法)
  • v-on指令的作用是绑定事件,简写@
  • 方法中通过this关键字获取data中的数据
  • v-text指令的作用是:设置元素的文本值,简写{{}}
  • v-html指令的作用是:设置元素的innerHTML

v-show指令

<body>
    <div id="app">
        <input type="button" value="切换显示状态" @click="changeIsShow">
        <input type="button" value="累加年龄" @click="addAge">
        <img v-show="isShow" src="D:\Study\壁纸\1.jpg" alt="" width="100px" height="100px">
        <img v-show="age>18" src="C:\Users\廖洪四\Desktop\廖洪四.jpg" alt="" width="100px" height="100px">
    </div>
    <script>
        var app =new Vue({
            el:'#app',
            data:{
                isShow:false,
                age:17
            },
            methods:{
                changeIsShow:function(){
                    this.isShow=!this.isShow
                },
                addAge:function(){
                    this.age++
                }
            }
        })
    </script>
</body>

知识点:

  • v-show指令的作用是:根据真假切换元素的显示状态
  • 原理是修改元素的display属性,实现显示隐藏
  • 指令后面的内容,最终都会解析为布尔值
  • 值为true元素显示,false元素隐藏
  • 数据改变之后,对应元素的显示状态会同步更新

v-if指令

<body>
    <div id="app">
        <input type="button" value="切换显示" @click="toggleIsShow">
        <p v-show='isShow'>廖洪四</p>
        <p v-if='temprature>=35'>热死了 v-if显示</p>
    </div>

    <script>
        var app=new Vue({
            el:'#app',
            data:{
                isShow:false,
                temprature:40
            },
            methods:{
                toggleIsShow:function(){
                    this.isShow=!this.isShow
                }
            }
        })
    </script>
</body>

知识点:

  • v-if指令的作用是:根据表达式的真假切换元素的显示状态
  • 本质是通过操作dom元素来切换显示状态
  • 表达式为true,元素存在于dom树中,否则从dom树中移除
  • 频繁的切换用v-show(消耗少),反之使用v-if

v-bind指令

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

知识点:

  • v-bind指令的作用是为元素绑定属性,完整写法是:v-bind:属性名
  • 简写可以直接省略v-bind,只保留:属性名
  • 需要动态的增删class建议使用对象的方式

图片切换

<body>
		<div id="mask">
        <div class="center">
            <h2 class="title"><img src="http://www.itheima.com/images/logo.png">xxxxxxxx</h2>
            <img :src="imgArr[index]" alt="" width="200" height="200" />
            <a href="javascript:void(0)" class="left" @click="prev" v-show="index!=0">
            	<img src="img/prev.jpg" alt="" width="200" height="200"/>
            </a>
            <a href="javascript:void(0)" class="right" @click="next" v-show="index<imgArr.length-1">
            	<img src="img/next.jpg" alt="" width="200" height="200"/>
            </a>
        </div>
    </div>
    <script>
        var app=new Vue({
            el:'#mask',
            data:{
                imgArr:[
                	"img/1.jpg",
                	"img/2.jpg",
                	"img/3.jpg",
                ],
                index:0
            },
            methods:{
                 prev:function(){
                 	this.index--
                 },
                 next:function(){
                 	this.index++
                 }
            }
        })
    </script>
	</body>

知识点:

  • 列表数据使用数组保存
  • v-bind指令可以设置元素属性,比如src
  • v-show和v-if指令可以切换元素的显示状态,频繁切换使用v-show

v-for指令

<body>
    <div id="app">
        <input type="button" value="添加数据" @click="add">
        <input type="button" value="移除数据" @click="remove">
        <ul>
            <li v-for="(item,index) in arr">
                {{ index+1 }}校区:{{ item }}
            </li>
            <li v-for="(item,index) in vegetables" v-bind:title="item.name">
                {{ item.name }}
            </li>
        </ul>
    </div>
    <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-for指令的作用是:根据数据生成列表结构
  • 数组经常和v-for结合使用
  • 语法是:(item,index) in 数据
  • item和index可以和其它指令一起使用,比如v-bind指令
  • 数组长度的更新会同步到页面上,是响应式的

v-on补充

<body>
    <div id="app">
        <input type="button" value="点击" @click="doIt(666,'老大')">
        <input type="text" @keyup.enter="sayHi">
    </div>
    <script>
        var app =new Vue({
            el:'#app',
            methods:{
                doIt:function(p1,p2){
                    console.log("hello");   
                    console.log(p1);
                    console.log(p2);
                },
                sayHi:function(){
                    alert("吃了没")
                }
            }
        })
    </script>
</body>

知识点:

  • 事件绑定的方法写成函数调用的形式,可以传入自定义参数
  • 定义方法时需要定义形参来接收传入的实参
  • 事件的后面跟上 .修饰符 可以会事件进行限制
  • .enter 可以限制出发的按键为回车
  • 事件修饰符有两种

v-model指令

<body>
    <div id="app">
        <input type="button" value="修改message" @click="setM">
        <input type="text" v-model="message" @keyup.enter="getM">
        <h5>{{ message }}</h5>
    </div>
    <script>
        var app =new Vue({
            el:'#app',
            data:{
                message:'好耶好耶'
            },
            methods:{
                getM:function(){
                    alert(this.message)
                },
                setM:function(){
                    this.message="不行不行"
                }
            }
        })
    </script>
</body>

知识点:

  • v-model指令的作用是便捷的设置和获取表单元素的值
  • 绑定的数据 和 表单元素的值 相关联,无论修改哪一个的值,另一个的值都会相应改变

小黑记事本

<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>{{ index+1 }}.</span>
							<label>{{ item }}</label>
							<button class="destory" @click="remove(index)">删除</button>
						</div>
					</li>
				</ul>
			</section>
			<footer class="footer">
				<span class="todo-count" v-if="list.length!=0">
					<strong>{{ list.length }}</strong>
					items left
					<button class="clear-complted" @click="clear" v-show="list.length!=0">clear</button>
				</span>
			</footer>
		</section>
		<footer class="info">
			<p>
				<a href="http://www.itheima.com"><img src="img/logo.png" alt="..."></a>
			</p>
		</footer>
		<script>
			var app=new Vue({
				el:'#todoapp',
				data:{
					list:["写代码","学英语","玩游戏"],
					inputValue:"好好学习,天天向上"
				},
				methods:{
					add:function(){
						this.list.push(this.inputValue);
					},
					remove:function(index){
						this.list.splice(index,1);//一次删一个
					},
					clear:function(){
						this.list=[];
					}
				}
			})
		</script>
	</body>

知识点:

  • 新增功能
    • v-for指令的作用:根据一个数组生成一个列表结构
    • v-model指令的作用:双向绑定数据(把表单元素的数据跟data中的数据关联起来),方便设置和取值
    • v-on指令:绑定事件,结合事件修饰符作一些限制(.enter限制触发的按键)
    • 通过审查元素快速定位
  • 删除功能
    • 数据改变,和数据绑定的元素同步改变
    • 事件可以接收自定义参数
  • 统计功能
    • 基于数据的开发方式
  • 清空功能
    • 将列表设置为空
  • 隐藏
    • 没有数据时,隐藏元素(v-show v-if 数组非空)

网络应用

天气预报(天知道)

<body>
    <div class="wrap" id="app">
        <div class="search_form">
            <div class="logo">
                <h3>天知道logo</h3>
            </div>
            <div class="form_group">
                <input @keyup.enter="searchWeather" v-model="city" type="text" class="input_txt" placeholder="请输入查询的城市">
                <button class="input_sub">搜 索</button>
            </div>
            <div class="hotkey">
                <a href="javascript:;" @click="changeCity('北京')">北京</a>
                <a href="javascript:;" @click="changeCity('上海')">上海</a>
                <a href="javascript:;" @click="changeCity('广州')">广州</a>
                <a href="javascript:;" @click="changeCity('深圳')">深圳</a>
            </div>
        </div>
        <ul class="weather_list">
            <li v-for="item in weatherList">
                <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>
        var app = new Vue({
        el:'#app',
        data:{
            city:'',
            weatherList:[]
        },
        methods:{
            searchWeather:function(){
                // console.log('天气查询');
                // console.log('武汉');
                //调用接口
                //保存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){ })
            },
            changeCity:function(city){
                this.city=city;
                this.searchWeather();
            }
        }
    })
    </script>
</body>

知识点:

  • axios回调函数中的this指向改变了,需要额外存一份
  • 服务器返回的数据比较复杂时,获取的时候需要注意层级结构
  • 自定义参数可以让代码的复用性更高
  • methods中定义的方法内部,可以通过this关键字点出其它的方法

综合应用

<!DOCTYPE html>
<html lang="en">

<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>
  <!-- 样式 -->
<!--  <link rel="stylesheet" href="./css/index.css">-->
  <style type="text/css">
    body,
    ul,
    dl,
    dd {
      margin: 0px;
      padding: 0px;
    }

    .wrap {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: url("https://i.loli.net/2020/03/23/gz9abCBAcphv6jF.jpg") no-repeat;
      background-size: 100% 100%;
    }

    .play_wrap {
      width: 800px;
      height: 544px;
      position: fixed;
      left: 50%;
      top: 50%;
      margin-left: -400px;
      margin-top: -272px;
      /* background-color: #f9f9f9; */
    }

    .search_bar {
      height: 60px;
      background-color: #1eacda;
      border-top-left-radius: 4px;
      border-top-right-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      z-index: 11;
    }

    .search_bar img {
      margin-left: 23px;
    }

    .search_bar input {
      margin-right: 23px;
      width: 296px;
      height: 34px;
      border-radius: 17px;
      border: 0px;
      background: url("https://i.loli.net/2020/03/23/9FeKnVlohsY3krO.png") 265px center no-repeat
      rgba(255, 255, 255, 0.45);
      text-indent: 15px;
      outline: none;
    }

    .center_con {
      height: 435px;
      background-color: rgba(255, 255, 255, 0.5);
      display: flex;
      position: relative;
    }

    .song_wrapper {
      width: 200px;
      height: 435px;
      box-sizing: border-box;
      padding: 10px;
      list-style: none;
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 1;
    }

    .song_stretch {
      width: 600px;
    }

    .song_list {
      width: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      height: 100%;
    }
    .song_list::-webkit-scrollbar {
      display: none;
    }

    .song_list li {
      font-size: 12px;
      color: #333;
      height: 40px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      width: 580px;
      padding-left: 10px;
    }

    .song_list li:nth-child(odd) {
      background-color: rgba(240, 240, 240, 0.3);
    }

    .song_list li a {
      display: block;
      width: 17px;
      height: 17px;
      background-image: url("https://i.loli.net/2020/03/23/chJ89uNpofneFrS.png");
      background-size: 100%;
      margin-right: 5px;
      box-sizing: border-box;
    }

    .song_list li b {
      font-weight: normal;
      width: 122px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .song_stretch .song_list li b {
      width: 200px;
    }

    .song_stretch .song_list li em {
      width: 150px;
    }

    .song_list li span {
      width: 23px;
      height: 17px;
      margin-right: 50px;
    }
    .song_list li span i {
      display: block;
      width: 100%;
      height: 100%;
      cursor: pointer;
      background: url("https://i.loli.net/2020/03/23/HFyBnJ5loLhI7qK.png") left -48px no-repeat;
    }

    .song_list li em,
    .song_list li i {
      font-style: normal;
      width: 100px;
    }

    .player_con {
      width: 400px;
      height: 435px;
      position: absolute;
      left: 200px;
      top: 0px;
    }

    .player_con2 {
      width: 400px;
      height: 435px;
      position: absolute;
      left: 200px;
      top: 0px;
    }

    .player_con2 video {
      position: absolute;
      left: 20px;
      top: 30px;
      width: 355px;
      height: 265px;
    }

    .disc {
      position: absolute;
      left: 73px;
      top: 60px;
      z-index: 9;
    }
    .cover {
      position: absolute;
      left: 125px;
      top: 112px;
      width: 150px;
      height: 150px;
      border-radius: 75px;
      z-index: 8;
    }
    .comment_wrapper {
      width: 180px;
      height: 435px;
      list-style: none;
      position: absolute;
      left: 600px;
      top: 0px;
      padding: 25px 10px;
    }
    .comment_wrapper .title {
      position: absolute;
      top: 0;
      margin-top: 10px;
    }
    .comment_wrapper .comment_list {
      overflow: auto;
      height: 410px;
    }
    .comment_wrapper .comment_list::-webkit-scrollbar {
      display: none;
    }
    .comment_wrapper dl {
      padding-top: 10px;
      padding-left: 55px;
      position: relative;
      margin-bottom: 20px;
    }

    .comment_wrapper dt {
      position: absolute;
      left: 4px;
      top: 10px;
    }

    .comment_wrapper dt img {
      width: 40px;
      height: 40px;
      border-radius: 20px;
    }

    .comment_wrapper dd {
      font-size: 12px;
    }

    .comment_wrapper .name {
      font-weight: bold;
      color: #333;
      padding-top: 5px;
    }

    .comment_wrapper .detail {
      color: #666;
      margin-top: 5px;
      line-height: 18px;
    }
    .audio_con {
      height: 50px;
      background-color: #f1f3f4;
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
    }
    .myaudio {
      width: 800px;
      height: 40px;
      margin-top: 5px;
      outline: none;
      background-color: #f1f3f4;
    }
    /* 旋转的动画 */
    @keyframes Rotate {
      from {
        transform: rotateZ(0);
      }
      to {
        transform: rotateZ(360deg);
      }
    }
    /* 旋转的类名 */
    .autoRotate {
      animation-name: Rotate;
      animation-iteration-count: infinite;
      animation-play-state: paused;
      animation-timing-function: linear;
      animation-duration: 5s;
    }
    /* 是否正在播放 */
    .player_con.playing .disc,
    .player_con.playing .cover {
      animation-play-state: running;
    }

    .play_bar {
      position: absolute;
      left: 200px;
      top: -10px;
      z-index: 10;
      transform: rotate(-25deg);
      transform-origin: 12px 12px;
      transition: 1s;
    }
    /* 播放杆 转回去 */
    .player_con.playing .play_bar {
      transform: rotate(0);
    }
    /* 搜索历史列表 */
    .search_history {
      position: absolute;
      width: 296px;
      overflow: hidden;
      background-color: rgba(255, 255, 255, 0.3);
      list-style: none;
      right: 23px;
      top: 50px;
      box-sizing: border-box;
      padding: 10px 20px;
      border-radius: 17px;
    }
    .search_history li {
      line-height: 24px;
      font-size: 12px;
      cursor: pointer;
    }
    .switch_btn {
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
    }
    .right_line {
      position: absolute;
      left: 0;
      top: 0;
    }
    .video_con video {
      position: fixed;
      width: 800px;
      height: 546px;
      left: 50%;
      top: 50%;
      margin-top: -273px;
      transform: translateX(-50%);
      z-index: 990;
    }
    .video_con .mask {
      position: fixed;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      z-index: 980;
      background-color: rgba(0, 0, 0, 0.8);
    }
    .video_con .shutoff {
      position: fixed;
      width: 40px;
      height: 40px;
      background: url("https://i.loli.net/2020/03/23/ZWSChyBwjA5uRfL.png") no-repeat;
      left: 50%;
      margin-left: 400px;
      margin-top: -273px;
      top: 50%;
      z-index: 995;
    }
  </style>
</head>

<body>
  <div class="wrap">
    <div class="play_wrap" id="player">
      <div class="search_bar">
        <img src="https://sm.ms/image/FO95hAIXyZqoHct" alt="" />
        <!-- 搜索歌曲 -->
        <input type="text" placeholder="输入要搜索的Music" 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="https://i.loli.net/2020/03/23/dor23bhZtIvK17X.png" class="switch_btn" alt="">
        </div>
        <!-- 歌曲信息容器 -->
        <div class="player_con" :class="{playing:isPlay}">
          <img src="https://i.loli.net/2020/03/23/gZHko2WlpJNcGPv.png" class="play_bar" />
          <!-- 黑胶碟片 -->
          <img src="https://i.loli.net/2020/03/23/hQPuH4gNRx7XayI.png" class="disc autoRotate" />
          <img :src="coverUrl==''?'https://i.loli.net/2020/03/23/QEL4rdy5KCsn3cz.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="https://i.loli.net/2020/03/23/dor23bhZtIvK17X.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>

</html>

知识点:

  • 歌曲搜索
    • 服务器返回的数据比较复杂时,获取的时候需要注意层级结构
    • 通过审查元素快速定位到需要操纵的元素
  • 歌曲播放
    • 歌曲id依赖歌曲搜索的结果,对于不用的数据也需要关注
  • 歌曲封面
    • 在vue中通过v-bind指令操作属性(如上面img的src属性)
    • 本地无法获取的数据,基本都会有对应的接口
  • 歌曲评论
    • 在vue中通过v-for生成列表
  • 播放动画
    • audio标签的play事件会在音频播放的时候触发
    • audio标签的pause事件会在音频暂停的时候触发
    • 通过对象的方式设置类名,类名生效与否取决于后面值得真假
  • 播放mv
    • 不同的接口需要的数据是不同的,文档的阅读需要仔细
    • 页面结构复杂以后,通过审查元素的方式去快速定位相关元素
    • 响应式的数据都需要定义在data中

来源:前端基础必会教程-4个小时带你快速入门vue

本文出自:Vue快速入门