Vue -- 指令【学习笔记】(持续更新)

Vue – 指令【学习笔记】(持续更新)

记录了Vue第三天的学习笔记

v-show

注意,v-show 不支持 <template> 元素,也不支持 v-else

带有 v-show 的元素始终会被渲染并保留在 DOM 中。v-show 只是简单地切换元素的 CSS property display

<div id="app">
    <div v-show="shouye">首页</div>
    <div v-show="dongman">动漫</div>
    <div v-show="yinyue">音乐</div>
</div>
let app = new Vue({
    el: "#app",
    data: {
        shouye: true,
        dongman: false,
        yinyue: false,
    }
})

上面的执行结果只会展示首页

v-on:click 简写 @click

用法一:直接在双引号中写函数名

<div id="app">
    <div v-show="shouye">首页</div>
    <div v-show="dongman">动漫</div>
    <div v-show="yinyue">音乐</div>
    <!-- 注意函数名不能和变量名重名 -->
    <button @click="shouYe">首页</button>
    <button @click="dongMan">动漫</button>
    <button @click="yinYue">音乐</button>
</div>
let app = new Vue({
    el: "#app",
    data: {
        shouye: true,
        dongman: false,
        yinyue: false,
    },
    methods: {
        shouYe: function(e){
            // console.log(e);
            this.shouye = true;
            this.dongman = false;
            this.yinyue = false;
        },
        dongMan: function(e){
            this.dongman = true;
            this.shouye = false;
            this.yinyue = false;
        },
        yinYue: function(e){
            this.yinyue = true;
            this.shouye = false;
            this.dongman = false;
        }
    }
})

按钮点击页面跳转

用法二:在双引号中写表达式

<div id="app">
    <h1>点击次数:{{ count }}</h1>
    <!-- 可以使用表达式完成事件操作 -->
    <button type="button" @click="count++">点击加一</button>
</div>
var app = new Vue({
    el: "#app",
    data: {
        count: 0
    }
})

用法三:事件传参

<div id="app">
    <ul>
        <li v-for="start,index in starts" @click="clickEvent(index,start,$event)">索引值:{{ index }}---内容:{{ start }}</li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        starts: ["蔡徐坤","范冰冰","李晨"]
    },
    methods: {
        clickEvent: function(index,start,event){
            console.log(index,start);
            console.log(event);
        }
    }
})

注意:要想既在函数中传参又想要得到 event, 则可以在传参时使用 $evnet

用法四:事件修饰符

  • stop修饰符,阻止冒泡事件向上传递
<div id="app">
    <!-- stop修饰符,阻止冒泡事件向上传递 -->
    <div class="btnParent" @click="clickParent">
        <button @click.stop="clickEvent">按钮</button>
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {

    },
    methods: {
        clickEvent: function(){
            console.log("clickEvent");
        },
        clickParent: function(){
            console.log("clickParent");
        }
    }
})

clickEvent

  • prevent修饰符,阻止默认事件
<form action="" method="post">
    <input type="text" name="username" id="" value="" />
    <!-- 阻止默认事件 -->
    <input @click.prevent="searchWeather" type="submit" value="提交"/>
</form>
<div id="weather">
    <h1>{{ tmp }}</h1>
    <h3>{{ brief }}</h3>
</div>
var app = new Vue({
    el: "#app",
    data: {
		city: "北京",
        tmp: "",
        brief: ""
    },
    methods: {
        searchWeather: function(){
            console.log("查询天气");
            console.log(this.city);
            let httpUrl = `https://free-api.heweather.net/s6/weather/now?location=${this.city}&key=3c497450d8e44c5280421ceaba1db581`
            let res = await fetch(httpUrl)
            let result = await res.json();
            console.log(result);
            let now = result.HeWeather6[0].now;
            this.tmp = now.tmp;
            this.brief = now.cond_txt;
        }
    }
})
  • once修饰符,只触发一次
<button type="button" @click.once="onceEvent">只触发一次的按钮</button>
var app = new Vue({
    el: "#app",
    data: {
		
    },
    methods: {
		onceEvent: function(){
            console.log("只触发一次");
        }
    }
})

只触发一次

  • keydown修饰符,指定按键

注意:表单默认为回车提交

keydown下有以下按键

.enter

.tab

.delete (捕获"删除"和"退格"键)

.esc

.space

.up

.down

.left

.right

还可以配置按键的自定义修饰符

Vue.config.keyCodes.f1 = 112
<form action="" method="post">
    <input type="text" @keydown.enter="searchWeather" name="username" v-model="city" id="" value="" />
        <!-- 阻止默认事件 -->
        <input @click.prevent="searchWeather" type="submit" value="提交"/>
            </form>
var app = new Vue({
    el: "#app",
    data: {
        city: "北京",
        tmp: "",
        brief: ""
    },
    methods: {
        searchWeather: function(){
            console.log("查询天气");
            console.log(this.city);
            let httpUrl = `https://free-api.heweather.net/s6/weather/now?location=${this.city}&key=3c497450d8e44c5280421ceaba1db581`
            let res = await fetch(httpUrl)
            let result = await res.json();
            console.log(result);
            let now = result.HeWeather6[0].now;
            this.tmp = now.tmp;
            this.brief = now.cond_txt;
        }
    }
})
  • exact修饰符,精确触发

只有在只按ctrl后再点击触发,如果多按了其他键再点击则不会触发

<button type="button" @click.ctrl.exact="ctrlEvent">按住ctrl点击</button>
ctrlEvent: function(){
    console.log("按住ctrl点击");
}

v-for

<div id="app">
    <h3>循环列表</h3>
    <ul>
        <li v-for="student in students">
            <h1>姓名:{{ student.studentName }}</h1>
            <p>年龄:{{ student.age }}---学校:{{ student.school }}</p>
        </li>
    </ul>
    <h3>条件+循环渲染(将偶数年龄的学生渲染出来),先循环再判断</h3>
    <ul>
        <li v-for="student,index in students" v-if="student.age%2==0" :key="index">
            <h1>索引:{{ index }}---姓名:{{ student.studentName }}</h1>
            <p>年龄:{{ student.age }}---学校:{{ student.school }}</p>
        </li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        students: [
            {
                studentName: "小明",
                age: 16,
                school: "清华"
            },
            {
                studentName: "小黑",
                age: 17,
                school: "北大"
            },
            {
                studentName: "小红",
                age: 18,
                school: "浙大"
            },
            {
                studentName: "小樱",
                age: 19,
                school: "河软"
            },
        ]
    }
})

computed(计算属性)

会将计算结果进行缓存,只要this.firstname和this.lastname变量的内容不改变,就不会重新计算

<div id="app">
    <!-- 计算属性 -->
    <div>{{ fullname }}</div>
    <!-- 逆序显示1个单词 -->
    <h1>{{ reverseWord }}</h1>
    <h1>循环偶数年龄</h1>
    <ul>
        <li v-for="student in oddStudents">
            <h3>{{ student.studentName }}</h3>
            <h4>{{ student.age }}</h4>
        </li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        firstname: "张",
        lastname: "三",
        word: "music",
        students: [
            {
                studentName: "小明",
                age: 16,
                school: "清华"
            },
            {
                studentName: "小黑",
                age: 17,
                school: "北大"
            },
            {
                studentName: "小红",
                age: 18,
                school: "浙大"
            },
            {
                studentName: "小樱",
                age: 19,
                school: "河软"
            },
        ]
    },
    computed: {
        fullname: function(){
            // 会将计算结果进行缓存,只要this.firstname和lastname变量的内容不改变,就不会重新计算
            return this.firstname + this.lastname
        },
        reverseWord: {
            get: function(){
                return this.word.split("").reverse().join("")
            },
            set: function(val){
                this.word = val.split("").reverse().join("")
            }
        },
        oddStudents: function(){
            let results = this.students.filter((student,index)=>{
                return student.age%2 == 0
            })
            return results
        }
    }
})

v-once

<div id="app">
    <!-- 一次性插值,不再修改 -->
    <h1 v-once>{{ msg }}</h1>
</div>
var app = new Vue({
    el: "#app",
    data: {
        msg: "hello vue",
    }
})
app.msg = "hello 前端"

结果还是 hello vue

v-html

<div id="app">
    <!-- 插入HTML内容 -->
    <h1 v-html="htmlText"></h1>
</div>
var app = new Vue({
    el: "#app",
    data: {
        htmlText: "<span>hello</span>",
    }
})

hello

v-bind:id 简写 :id

#login{
    color: red;
}
#register{
    color: aqua;
}
<div id="app">
    <!-- 修改属性内容 -->
    <div :id="idname">
        <h1>登录</h1>
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        idname: "login",
    }
})

设置 idname 的值就是设置 div里的 id 的值

例如,设置 idname: “login”,其登录的颜色就会去CSS样式中寻找 #login 的属性,然后把字体渲染为红色,如果改为 “register”,则会把字体颜色修改为aqua

模板语言的表达式应用

<div id="app">
    <!-- 模板语言的表达式应用 -->
    <div>
        {{ firstname + lastname }}
    </div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        firstname: "张",
        lastname: "三",
    }
})

张三

watch(侦听器)

<div id="app">
    {{ msg }}
    <ul>
        <li v-for="item in arr">{{ item }}</li>
    </ul>
</div>
var app = new Vue({
    el: "#app",
    data: {
        msg: "hello Vue",
        arr: ["小明","小红","小黑"]
    },
    watch: {
        // val为修改的值
        msg: function(val){
            console.log("监听事件------msg");
            console.log(val);
        },
        arr: function(val){
            console.log("监听事件------arr");
            console.log(val);
        }
    }
})

修改 data 中属性的值会触发 watch,例如

app.msg = “hello”,watch会去监听msg

v-bind:class 简写 :class

.page {
    width: 200px;
    height: 200px;
    background: skyblue;
    display: none;
}
.active {
    display: block;
}
.col-xs-12 {
    display: block;
}
.red-bg {
    background: #FF0000;
}
.abc {
    display: block;
    background: yellow;
}
<div id="app">
    <!-- 通过对象的方式决定是否存在某个类 -->
    <div class="page" :class="{active:isTrue}"></div>
    <!-- 直接放置对象 -->
    <div class="page" :class="styleObj"></div>
    <!-- 放置数组 -->
    <div class="page" :class="styleArr"></div>
    <!-- 放置字符串 -->
    <div class="page" :class="styleStr"></div>
    <!-- 数组和对象混合使用 -->
    <div class="page" :class="styleArrObj"></div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        isTrue: false,
        // 放置对象
        styleObj: {
            "active": true,
            "laochen": true,
            "col-lg-6": true
        },
        // 可直接用数组的方式进行添加和删除
        styleArr: [
            "col-xs-12",
            "red-bg"
        ],
        // 放置字符串
        styleStr: "page abc def",
        // 数组和对象混合使用
        styleArrObj: [
            "abcd",
            {
                active: true
            }
        ]
    }
})

v-bind:style 简写 :style

<div id="app">
    <div style="width: 100px;height: 100px;background: skyblue;"></div>
    <!-- CSS内联样式变量拼接 -->
    <div style="width: 100px;height: 100px;background: skyblue;" :style="{ border: borderWidth+'px solid '+borderColor }"></div>
    <!-- CSS内联样式放置对象 -->
    <div :style="styleObj"></div>
    <!-- CSS数组的方式拼接 -->
    <div :style="styleArr"></div>
</div>
var app = new Vue({
    el: "#app",
    data: {
        borderWidth: 50,
        borderColor: "red",
        styleObj: {
            width: "200px",
            height: "300px",
            padding: "50px",
            "background-color": "skyblue"
        },
        styleArr: [
            {
                width: "200px",
                height: "300px",
                padding: "50px",
                "background-color": "skyblue"
            },
            {
                border: "30px solid yellow"
            }
        ]
    }
})

例如:CSS内联样式变量拼接 — 会将第二个div的边框设置为50px的红色边框

v-model

你可以用 v-model 指令在表单 <input> <textarea><select> 元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但 v-model 本质上不过是语法糖。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。

  • 单行文本输入框
<div id="app">
    <input type="" name="" v-model="username" value="" />
    <p>{{ username }}</p>
</div>
var app = new Vue({
    el: "#app",
    data: {
        username: "张三"
    }
})

v-model把 value值和username变量的值绑定在一起,实现了修改value的值就会自动修改username变量的值,这就是数据的双向绑定

  • 多行文本输入框
<textarea rows="" cols="" v-model="username"></textarea>
var app = new Vue({
    el: "#app",
    data: {
        username: "张三"
    }
})
  • 复选框:选择喜欢的水果
<span v-for="fruit in fruits">
    {{ fruit }}
    <input type="checkbox" name="fruit" id="" v-model="checkFruits" :value="fruit" />
</span>
<h2>{{ checkFruits }}</h2>
var app = new Vue({
    el: "#app",
    data: {
        fruits: ["苹果","香蕉","雪梨","葡萄"],
        checkFruits: []
    }
})

当选择内容时,会依次添加到 v-model绑定的checkFruits数组中去

  • 单选框:选择你最喜欢的水果
<span v-for="fruit in fruits">
    {{ fruit }}
    <input type="radio" name="zfruit" id="" v-model="radioFruit" :value="fruit" />
</span>
<h2>{{ radioFruit }}</h2>
var app = new Vue({
    el: "#app",
    data: {
        fruits: ["苹果","香蕉","雪梨","葡萄"],
        radioFruit: ""
    }
})

当选择内容时,会将 你最后一次点击的内容添加到radioFruit字符串中去

  • 选项框:选择你居住的城市
<select v-model="chooseCity">
    <option disabled value="">请选择</option>
    <option v-for="city in citys" :value="city">{{ city }}</option>
</select>
<h3>{{ chooseCity }}</h3>
var app = new Vue({
    el: "#app",
    data: {
        citys: ["北京","上海","深圳","广州"],
        chooseCity: ""
    }
})

把选中的值和chooseCity空字符串绑定在一起,实现数据的双向绑定

  • 选项框:选择你喜欢的城市

multiple属性实现选项框多选

<select v-model="moreCity" multiple="multiple">
    <option disabled value="">请选择</option>
    <option v-for="city in citys" :value="city">{{ city }}</option>
</select>
<h3>{{ moreCity }}</h3>
var app = new Vue({
    el: "#app",
    data: {
        citys: ["北京","上海","深圳","广州"],
        moreCity: []
    }
})

按住CTRL键,选择你喜欢的城市,把value的值和moreCity数组的值绑定到一起,实现数据的双向绑定

  • 将字符串变为数字获取

.number

<input type="text" name="age" v-model.number="age" value="" />
var app = new Vue({
    el: "#app",
    data: {
        age: 16
    },
    watch: {
        // 监听age变量的值的变化
        age: function(val){
            console.log(val);
        }
    }
})

加上.number后,value的值只能为数字时才能与 age数据双向绑定

  • lazy修饰符

在输入文字结束后,输入框的值才会与数据进行同步,节省性能

<input type="" name="" v-model.lazy="username" value="" />
var app = new Vue({
    el: "#app",
    data: {
        username: "张三"
    }
})
  • trim修饰符

去除输入内容两边的空格

<input type="" name="" v-model.lazy.trim="username" value="" />
var app = new Vue({
    el: "#app",
    data: {
        username: "张三"
    }
})

v-bind:is 简写 :is

:is 里面写需要显示的组件

例如:

<div id="app">
    <div id="content">
        <component :is="com"></component>
    </div>

    <button @click="chooseContent(1)">首页</button>
    <button @click="chooseContent(2)">列表</button>
    <button @click="chooseContent(3)">新闻</button>
    <button @click="chooseContent(4)">个人</button>
</div>
let com1 = Vue.component("index-com",{
    template: "<h1>首页内容</h1>",
})
let com2 = Vue.component("index-com",{
    template: "<h1>列表内容</h1>",
})
let com3 = Vue.component("index-com",{
    template: "<h1>新闻内容</h1>",
})
let com4 = Vue.component("index-com",{
    template: "<h1>个人内容</h1>",
})

var app = new Vue({
    el: "#app",
    data: {
        com: com1
    },
    methods: {
        chooseContent: function(id){
            // console.log(id);
            // console.log(this);
            // 通过获取id,选择注册好的组件
            this.com = this.$options.components["com"+id]
        }
    },
    components: {
        com1,com2,com3,com4
    }
})

当com的值为 com1 时,会显示首页的内容

当com的值为 com2 时,会显示列表的内容

当com的值为 com3 时,会显示新闻的内容

当com的值为 com4 时,会显示个人的内容

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码小余の博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值