1. 首页
  2. 技术知识

vue.js快速入门

el:挂载点


Vue实例的作用范围是什么呢?


Vue会管理el选项
命中的元素
及其内部的
后代元素


是否可以使用其他的选择器?


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


是否可以设置其他的dom元素呢?


可以使用其他的双标签,不能使用
HTML

BODY

<!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>el:挂载点</title></head><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></html>

data:数据对象


Vue中用到的数据定义在
data



data中可以写
复杂类型
的数据


渲染复杂类型数据时,遵守js的
语法
即可

<div id=”app”>    {{ message }} </div>var app = new Vue({            el:”#app”,                        data:{              message:”黑马程序员”,             array:[],             obj:{},                        }        })
Vue指令
指的是,以
v-
开头的一组特殊语法


v-text


v-text
指令的作用是:设置标签的内容(textContent)


默认写法会替换全部内容,使用
差值表达式{{}}
可以替换指定内容


内部支持写
表达式

<div id=”app”>          <h2 v-text=”message+’!’”></h2>          <h2>深圳{{ message + “!”}}</h2>        </div>var app = new Vue({       el:”#app”,                   data:{                message:”黑马程序员”            }        })
v-html


v-html
指令的作用是:设置元素的
innerHTML


内容中有
html
结构会被解析为
标签


v-text
指令无论内容是什么,只会解析为
文本


解析文本使用
v-text
,需要解析
html
结构使用
v-html

<div id=”app”>          <p v-html=“content”></p>        </div> var app = new Vue({            el:”#app”,                      data:{                // content:”黑马程序员”                content:”<a href=’#’>黑马程序员</a>”            }        })
v-on基础


v-on
指令的作用是:为元素绑定
事件


事件名不需要写
on


指令可以简写为
@


绑定的方法定义在
methods
属性中


方法内部通过
this
关键字可以访问定义在
data
中数据


事件绑定的方法写成
函数调用
的形式,可以传入自定义参数


定义方法时需要定义
形参
来接收传入的实参


事件的后面跟上
.修饰符
可以对事件进行限制

v-on补充


.enter
可以限制触发的按键为回车


事件修饰符有多种

<div id=”app”>          <input type=”button” value=”事件绑定” v-on:click=“doIt”>          <input type=”button” value=”事件绑定” v-on:monseenter=“doIt”>          <input type=”button” value=”事件绑定” v-on:dblclick=“doIt”>          <input type=”button” value=”事件绑定” @dblclick=“doIt”>        </div> var app = new Vue({            el:”#app”,                        methods:{           doIt:functiоn(){                // 逻辑              }            }        })<div class=”input-num”>            <button @click=“sub”>-</button>            <span>{{ num }}</span>            <button @click=“add”>+</button> </div><!– 开发环境版本,包含了有帮助的命令行警告 –><script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script><!– 编码 –><script>    /*      1. data中定义num属性,类型是数字,渲染到2个按钮中间      2. 减号绑定点击事件,对应的方法名叫sub,大于0之前递减      3. 加号绑定点击事件,对应的方法名叫add,小于0之前累加    */    // 创建Vue实例    var app = new Vue({        el: “#app”,        data: {            // 修改的数字            num:1        },        methods: {            // 减            sub:functiоn(){                // console.log(“sub”);                // 递减                if(this.num>0){                    this.num–;                }else{                    alert(“别点啦,太小啦!”);                }            },            // 加            add:functiоn(){                // console.log(“add”);                // 累加                if(this.num<10){                    this.num++;                }else{                    alert(“别点啦,太大啦!”);                }            }        }    });</script><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:functiоn(p1,p2){                console.log(“做it”);                console.log(p1);                console.log(p2);            },            sayHi:functiоn(){                alert(“吃了没”);            }        },    })</script></body>
v-show


v-show
指令的作用是:根据真假切换元素的显示状态


原理是修改元素的display,实现显示隐藏


指令后面的内容,最终都会解析为
布尔值


值为
true
元素显示,值为
false
元素隐藏


数据改变之后,对应元素的显示状态会
同步更新

<body><div id=”app”>    <input type=”button” value=”切换显示状态” @click=”changeIsShow”>    <input type=”button” value=”累加年龄” @click=”addAge”>    <img v-show=”isShow” src=”./img/monkey.gif” alt=””>    </div><!– 1.开发环境版本,包含了有帮助的命令行警告 –><script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script><script>    var app = new Vue({        el:”#app”,        data:{            isShow:false,            age:9        },        methods: {            changeIsShow:functiоn(){                this.isShow = !this.isShow;            },            addAge:functiоn(){                this.age++;            }        },    })</script></body>
v-if


根据表达值的真假,切换元素的显示和隐藏(操纵dom元素)


频繁的切换
v-show
,反之使用
v-if
,前者的切换消耗小


本质是通过操纵
dom
元素来切换显示状态


表达式的值为
true
,元素存在于
dom
树中,为
false
,从
dom
树中移除

<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:functiоn(){                this.isShow = !this.isShow;            }        },    })</script></body>
v-bind


设置元素的属性(比如:
src
,
title
,
class
)


v-bind
指令的作用是:为元素绑定属性


完整写法是
v-bind:属性名


简写的话可以直接省略
v-bind
,只保留
:属性名


需要动态的增删
class
建议使用对象的方式

<body><div id=”app”>    <img v-bind:src=”imgSrc” alt=””>    <br>        <br>    </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:functiоn(){                this.isActive = !this.isActive;            }        },    })</script></body>
图片切换实例

<body><div id=”mask”>    <div class=”center”>        <h2 class=”title”><img src=”./images/logo.png” alt=””> 深圳创维校区环境</h2>        <img :src=”imgList[index]” alt=”” />        <a                href=”javascript:void(0)”                @click=”prev”                class=”left”                v-show=”index>0″        >            <img src=”./images/prev.png” alt=”” />        </a>        <a                href=”javascript:void(0)”                @click=”next”                class=”right”                v-show=”index<imgList.length-1″        >            <img src=”./images/next.png” alt=”” />        </a>    </div></div><script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script><script>    const app = new Vue({        el: “#mask”,        data: {            imgList: [                “./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() {                this.index–;            },            // 下一张            next() {                this.index++;            }        }    });</script></body>
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:functiоn(){                this.vegetables.push({ name:”花菜炒蛋” });            },            remove:functiоn(){                this.vegetables.shift();            }        },    })</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:functiоn(){                alert(this.message);            },            setM:functiоn(){                this.message =”酷丁鱼”;            }        },    })</script></body>记事本实例,添加、删除、清除、隐藏

<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: functiоn () {                this.list.push(this.inputValue);            },            remove: functiоn (index) {                console.log(“删除”);                console.log(index);                this.list.splice(index, 1);            },            clear: functiоn () {                this.list = [];            }        },    })</script></body>
axios


axios
必须先导入才可以使用


使用
get

post
方法即可发送对应的请求


then
方法中的回调函数会在请求成功或失败时触发


通过回调函数的形参可以获取响应内容,或错误信息


axios
回调函数中的
this
已经改变,无法访问到
data
中数据



this
保存起来,回调函数中直接使用保存的
this
即可


和本地应用的最大区别就是改变了
数据来源


自定义参数可以让代码的
复用性
更高


methods
中定义的方法内部,可以通过
this
关键字点出其他的方法

<script src=”https://unpkg.com/axios/dist/axios.min.js”></script>    axios.get(地址?key=value&key2=values).then(              functiоn(response)                                                        {},                                      functiоn(err)                                                        {}                        )           axios.post(地址,{key:value,key2:value2}).then(            functiоn(response)            {},            functiоn(err)            {}      )<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 = functiоn () {        axios.get(“https://autumnfish.cn/api/joke/list?num=6”)            // axios.get(“https://autumnfish.cn/api/joke/list1234?num=6”)            .then(functiоn (response) {                console.log(response);            },functiоn(err){                console.log(err);            })    }    /*         接口2:用户注册         请求地址:https://autumnfish.cn/api/user/reg         请求方法:post         请求参数:username(用户名,字符串)         响应内容:注册成功或失败     */    document.querySelector(“.post”).onclick = functiоn () {        axios.post(“https://autumnfish.cn/api/user/reg”,{username:”盐焗西兰花”})            .then(functiоn(response){                console.log(response);                console.log(this.skill);            },functiоn (err) {                console.log(err);            })    }</script></body><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:functiоn(){                // console.log(this.joke);                var that = this;                axios.get(“https://autumnfish.cn/api/joke”).then(functiоn(response){                    // console.log(response)                    console.log(response.data);                    // console.log(this.joke);                    that.joke = response.data;                },functiоn (err) {  })            }        },    })</script></body><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><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>                            </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>

原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/126514.html

联系我们