vue基本使用

vue

vue是一套构建用户界面的渐进式框架

vue 的使用方法

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

声明式渲染

<div id="app">
  {{ msg }}
</div>
var vm = new Vue({
    el: '#app',
    data: {
        msg: 'hello world'
    }
})
var v2 = new Vue({
    el:"#app2",
    data:{
        msgDate: "页面加载于: "+ new Date().toLocaleString()
    }
})

指令

v-text 和 v-html

用于显示文本信息

v-text的使用

<div id="app">
	<div v-text="msg"></div>
</div>
var v = new Vue({
    el: '#app',
    data:{
        msg: 'v-text指令用于显示文本!'
    }
})

v-html的使用

<div id="app2">
	<div v-html='mgsHtml'></div>
</div>
var v2 = new Vue({
    el: '#app2',
    data:{
        mgsHtml: '<h1>v-html可以插入代码片段(不推荐使用)</h1>'
    }
})

v-cloak

这个指令保持在元素上直到关联实例结束编译。和 CSS 规则如 [v-cloak] { display: none } 一起用时,这个指令可以隐藏未编译的 Mustache 标签直到实例准备完毕。

好处: 不会在页面中看到未加载成功的源码

[v-clock]{
	display: none;
}
<div id="app">
    <div v-clock>{{meg}}</div>
</div>
var v = new Vue({
    el: '#app',
    data: {
        meg: 'hello vue'
    }
})

v-pre

跳过编译过程,显示原始标签

<div id="app">
	<span v-pre>{{msg}}</span>
</div>
var v = new Vue({
    el:'#app',
    data: {
        msg: 'hello vue'
    }
})

效果: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FPNG8kaZ-1594021984884)(C:\Users\zBei\AppData\Roaming\Typora\typora-user-images\1580996678737.png)]

v-once

只渲染元素和组件一次。随后的重新渲染,元素/组件及其所有的子节点将被视为静态内容并跳过。这可以用于优化更新性能。

<div id="app">
	<span v-once>{{msg}}</span>
</div>
var v = new Vue({
    el:'#app',
    data: {
        msg: 'hello vue'
    }
})

v-if 和 v-else

<div id="app">
    <span v-if="seen">{{msg1}}</span>
    <span v-else="seen">{{msg2}}</span>
</div>
var v = new Vue({
    el:'#app',
    data: {
        seen: true,
        msg1: '我现在是true',
        msg2: '我现在是false'
    }
})

v-if-else-if

<div id="app">
    <div v-if="type === 'A'">
        A
    </div>
    <div v-else-if="type === 'B'">
        B
    </div>
    <div v-else-if="type === 'C'">
        C
    </div>
    <div v-else>
        Not A/B/C
    </div>
</div>
var v = new Vue({
    el:'#app',
    data:{
        type:'D'
    }
})

v-show

当值为true的时候,显示内容。false的时候不显示内容,和v-if的区别,在于v-show会提前渲染出来,而if不会提前渲染

<div id="app">
    <div v-show='flag'>看的见我</div>
    <button v-on:click='handler'>切换</button>
</div>
var v = new Vue({
    el: '#app',
    data:{
        flag:true
    },
    methods:{
        handler:function(){
            this.flag = !this.flag;
        }
    }
})

v-for

<div id="app">
    <h3>循环数组</h3>
    <ul v-for="item in arrays">
        <li>
            {{item}}
        </li>
    </ul>
    <h3>循环对象</h3>
    <ul v-for="obj in objects">
        <li>
            {{obj}}
        </li>
    </ul>
    <h2>-----------------------</h2>
    <ul v-for="(value,key) in objects">
        <li>
            {{key}}:{{value}}
        </li>
    </ul>
    <h2>-----------------------</h2>
    <ul v-for="(value,key,index) in objects">
        <li>
            {{index}}:{{key}}:{{value}}
        </li>
    </ul>
    <h3>循环整数</h3>
    <ul v-for="i in 10">
        <li>{{i}}</li>
    </ul>
</div>
var v = new Vue({
    el: '#app',
    data: {
        arrays:[
            '小米',
            '华为',
            '苹果'
        ],
        objects:{
            name: '小米',
            url: 'http:www.xiaomi.com',
            logo: 'mi'
        },
        i:0
    }
})

v-model

在表单控件或者组件上创建双向绑定。

<div id="app">
    <input type="text" v-model="msg">
    <div>{{msg}}</div>
</div>
var v = new Vue({
    el:'#app',
    data:{
        msg:''
    }
})

v-on

事件绑定

事件绑定。事件类型由参数指定。表达式可以是一个方法的名字或一个内联语句,如果没有修饰符也可以省略。

<div id="app">
    <div>{{num}}</div>
    <button v-on:click="num++">按钮1</button>
    <button @click="num++">按钮2</button>
    <button @click="jiayi()">按钮3</button>
    <button @click="jiayi">按钮4</button>
</div>
var v = new Vue({
    el:'#app',
    data: {
        num:0
    },
    methods:{
        jiayi:function(){
            this.num++//this相当于v.num
        }
    }
})
事件的基本使用
<div id="app">
    <div>{{msg}}</div>
    <button @click="handler1">无参函数</button>
    <button @click="handler2('hello',$event)">有参函数</button>
</div>
var v = new Vue({
    el:'#app',
    data: {
        msg:'默认值'
    },
    methods:{
        //默认无参的情况,event可以直接使用
        handler1:function(event){
            this.msg = "点击的是:"+event.target.innerHTML;
        },
        //有参数的情况下,需要在传递参数是添加$event
        handler2:function(text,event){
            this.msg = '点击的是:'+text+"-"+event.target.innerHTML;
        }
    }
})
事件修饰符
<div id="app">
    <div>{{num}}</div>
    <div @click="handler1">
        <!-- stop:阻止冒泡事件 -->
        <button @click.stop="handler2">点击</button>
    </div>
    <!-- prevent: 阻止默认事件 -->
    <a href="http://www.baidu.com" @click.prevent="handler3">百度</a>
</div>
var v = new Vue({
     el: '#app',
     data: {
         num:0
     },
     methods:{
         handler1:function(){
             alert(this.num);
         },
         handler2:function(){
             this.num++;
         },
         handler3:function(){
             alert("阻止了默认事件")
         }
     }
 })
按键修饰符
<h4>请打开控制台</h4>
<div id="app">
    <form action="">
        <div>
            用户名:
            <!-- @keyup.delete: 按下delete执行函数,@表示简写 -->
            <input type="text" v-model='uname' @keyup.delete="deletContent">
        </div>
        <div>
            密 码:
            <!-- v-on:keyup.enter: 按下回车执行函数 -->
            <input type="text" v-model='pwd' v-on:keyup.enter='enterSubmit'>
        </div>
        <button type="button" @click='btnSubmit'>登录</button>

    </form>
</div>
var v = new Vue({
    el:'#app',
    data:{
        uname:'',
        pwd:''
    },
    methods:{
        btnSubmit:function(){
            console.log(this.uname+"--"+this.pwd)
        },
        enterSubmit:function(){
            console.log(this.uname+"--"+this.pwd)
        },
        deletContent:function(){
            //清空uname的值
            this.uname='';
        }
    }
})
自定义按键
<h4>请打开控制台</h4>
<div id="app">
    请随意按下即可找到对应键码: <input type="text" v-on:keyup='handler'><br><br>
    方法1:只有按a才会打印文字: <input type="text" v-on:keyup.65="handlerA"><br><br>
    方法2:只有按a才会打印文字: <input type="text" v-on:keyup.aaa="handlerAAA"><br><br>
</div>
/*
	规则: 自定义按键修饰符名字是自定义的,但是对应的值必须是对应的键码(event.keyCode)
*/ 
//设置变局属性
Vue.config.keyCodes.aaa = 65;
var v = new Vue({
    el:'#app',
    methods:{
        handler:function(event){
            console.log(event.keyCode);
        },
        handlerA:function(){
            console.log("按下了a");
        },
        handlerAAA:function(){
            console.log("按下了aaa");
        }
    }
})

v-bind

数据的简单使用

<div id="app">
    v-bind:<a v-bind:href="url">百度</a>
    简写:<a :href="url">百度</a>
</div>
var v = new Vue({
    el:'#app',
    data:{
        url:'http://www.baidu.com'
    }
})
绑定样式

通过对象形式绑定class

.active{
    border: 1px #000 solid;
    width: 100px;
    height: 100px;
}
.error{
    background: #f00;
}
<!-- 通过对象形式来绑定属性,true则显示演示,false反之 -->
<div id="app">
    <div v-bind:class="{active:isActive,error:isError}">样式绑定</div>
    <button @click="handler">切换</button>
</div>
var v = new Vue({
    el:'#app',
    data:{
        isActive:true,
        isError:true
    },
    methods:{
        handler:function(){
            this.isActive=!this.isActive;
            this.isError=!this.isError;
        }
    }
})

通过数组绑定class样式

.active{
    border: 1px #000 solid;
    width: 100px;
    height: 100px;
}
.error{
    background: #f00;
}
<!-- 通过数字形式来绑定属性,并赋予样式值 -->
<div id="app2">
    <div v-bind:class="[activeArray,errorArray]">样式绑定之数组</div>
    <button @click="handler">切换</button>
</div>
var v = new Vue({
    el:'#app2',
    data:{
        activeArray:'active',
        errorArray:'error'
    },
    methods:{
        handler:function(){
            this.activeArray='';
            this.errorArray='';
        }
    }
})
绑定样式的简写
.active{
    width: 200px;
    height: 50px;
    border: 2px #f00 solid;
}
.error{
    background: #ccc;
}
.test{
    width: 200px;
    height: 50px;
    border: solid 5px #000;
}
.default{
    transform: translateX(20px);
}
<div id="app">
    <!-- 数组和对象结合使用 -->
    <div v-bind:class="[activeArr,errorArr,{test:isTest}]">数组结合对象使用</div>
    <!-- 使用vue中写数组的形式 -->
    <div v-bind:class="arrClasses">使用vue中写数组的形式</div>
    <!-- 使用vue中写对象的形式 -->
    <div v-bind:class="objClasses">使用vue中写对象的形式</div>
    <!-- 带有默认class -->
    <div class="default" v-bind:class="arrClasses">带有默认class</div>
    <button @click="handler">切换</button>
</div>
var v = new Vue({
    el:'#app',
    data:{
        activeArr:'active',
        errorArr:'error',
        isTest:true,
        arrClasses:['active','error'],
        objClasses:{
            active:true,
            test:true
        }
    },
    methods:{
        handler:function(){
            this.isTest = !this.isTest;
        }
    }
})

绑定style实现样式改变

<div id="app">
    <div v-bind:style="{border:borders,width:widths,height:heights}">v-bind:style</div>
    <div v-bind:style="objStyles">通过对象接收样式</div>
    <div v-bind:style="[objStyles,overrideStyles]">通过数组接收样式</div>
</div>
var v = new Vue({
    el:'#app',
    data:{
        borders:'solid 1px red',
        widths:'100px',
        heights:'50px',
        objStyles:{
            width:'100px',
            height:'100px',
            border:'solid 1px #000'
        },
        overrideStyles:{
            background:'#ccc',
            border:'solid 2px #f00'
        }
    }
})

表单

表单基本使用

<div id="app">
    <form action="">
        <div>
            <label for="uname">姓名:</label>
            <input type="text" id="uname" v-model="uname">
        </div>
        <div>
            <span>性别: </span>
            <input type="radio" id="man" value="man" v-model="gender">
            <label for="man"></label>
            <input type="radio" id="woman" value="woman" v-model="gender">
            <label for="woman"></label>
        </div>
        <div>
            <span>爱好: </span>
            <input type="checkbox" id="draw" value="draw" v-model="hobby">
            <label for="draw">画画</label>
            <input type="checkbox" id="dance" value="dance" v-model="hobby">
            <label for="dance">跳舞</label>
            <input type="checkbox" id="code" value="code" v-model="hobby">
            <label for="code">写代码</label>
        </div>
        <div>
            <span>职业: </span>
            <select v-model="occupation">
                <option value="0">请选择你的职业</option>
                <option value="lawyer">律师</option>
                <option value="teacher">教师</option>
                <option value="programmer">程序员</option>
            </select>
        </div>
        <div>
            <span>个人简介: </span>
            <textarea v-model="introduction"></textarea>
        </div>
        <button type="submit" @click.prevent="handler()">提交</button>
    </form>
</div>
var v = new Vue({
    el: '#app',
    data:{
        uname:'',
        gender:'man',
        hobby:['code'],
        occupation:'0',
        introduction:''
    },
    methods:{
        handler:function(){
            console.log("uname:"+this.uname+"--"+"gender:"+this.gender+"--"+"hobby:"+this.hobby);
            console.log("occupation:"+this.occupation);
            console.log("introduction:"+this.introduction);
        }
    }
})

表单修饰符

<div id="app">
    <form action="">
        <section>
            数字类型: <input type="text" v-model.number="age"> <br><br>
            去掉空格: <input type="text" v-model.trim="trim"> <br><br>
            lazy: <input type="text" v-model.lazy="lazy"> <br><br>
            <p>{{lazy}}</p>
            <button type="submit" @click.prevent="handler">提交</button>
        </section>
    </form>
</div>
var v = new Vue({
    el:'#app',
    data:{
        age:'',
        trim:'',
        lazy:''
    },
    methods:{
        handler:function(){
            console.log("number: "+this.age+2)
            console.log("去掉空格:"+this.trim.length)
            console.log("失去焦点后加载:"+this.trim)
        }
    }
})

计算机属性

表达式的计算逻辑可能会表复杂,使用计算机属性可以让模板内容更加简洁

计算机属性和方法的区别

  • 计算机有缓存机制,如果数据不便,不会在执行计算机属性。
  • 方法没有缓存机制。
<div id="app">
    <p>{{msg}}</p>
    <p>表达式:{{msg.split('').reverse().join('')}}</p>
    <p>计算机属性:{{reverseString}}</p>
</div>
var v = new Vue({
    el:'#app',
    data:{
        msg:'computed'
    },
    computed:{
        reverseString:function(){//相当于把数据当成方法执行
            return this.msg.split().reverse().join('-');
        }
    }
})

侦听器

Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。

<div id="app">
    <span>请输入用户名: </span>
    <input type="text" v-model.lazy="uname">
    <span v-bind:style="{color: colorStyle}">{{tip}}</span>
</div>
var v = new Vue({
    el:'#app',
    data:{
        uname:'',
        tip:'请输入用户名',
        colorStyle:'red'
    },
    methods:{
        handler:function(uname){
            //执行接口
            var that = this;
            setTimeout(function(){
                if(uname == 'admin'){
                    that.tip = '用户名已存在,请换一个'
                }else{
                    that.tip = '可以使用'
                }
            },2000)
        }
    },
    watch:{
        //用于检测数据是否改变
        uname:function(val){//val: 相当于里面的uname的值
            this.handler(val);//执行函数
            this.tip = '正在验证...'
        }
    }
})

过滤器

<h2>过滤器: </h2>
<div id="app">
    首字母大写: <input type="text" v-model='msg'>
    <p>{{msg|upper}}</p>
    <p>{{msg | upper | lower}}</p>
</div>
//下面写法为全局过滤器
// Vue.filter('upper',function(val){//val相当于获取值
//     return val.charAt(0).toUpperCase() + val.slice(1);
// })
Vue.filter('lower',function(val){
    return val.charAt(0).toLowerCase() + val.slice(1);
})

var v = new Vue({
    el:'#app',
    data:{
        msg:''
    },
    filters:{//为局部过滤器
        upper:function(val){
            return val.charAt(0).toUpperCase() + val.slice(1);
        }
    }
})

过滤器中传递多个参数

<div id="app">
    <span>{{date | format("yyyy-MM-dd")}}</span>
</div>
Vue.filter('format',function(value,arg1){
    if(arg1 == 'yyyy-MM-dd'){
        var dates = value.getFullYear()+"-"+(value.getMonth()+1)+"-"+value.getDate();
        return dates;
    }
})
var v = new Vue({
    el:'#app',
    data:{
        date:new Date()
    }
})

set方法

set方法用于设置数据/对象中的数据

用法

//方法一
Vue.set(数组/对象,下标/key,新的值)
Vue.set(数组/对象,下标/key,新的值)

//方法二
var v = new Vue({
    el:'#app',
    data:{
        array:[],
        obj:{id:'0',name:'Tom'}
    }
})
v.$set(数组/对象,下标/key,新的值)
v.$set(数组/对象,下标/key,新的值)

案例

<div id="app">
    <span>数组的数据:</span>
    <p v-for="item in arrayData">{{item}}</p>
    <span>对象中的数据</span>
    <div>
        <span>{{obj.name}}</span>
        -
        <span>{{obj.age}}</span>
        -
        <span>{{obj.gender}}</span>
    </div>
</div>
var v = new Vue({
    el:'#app',
    data:{
        arrayData:['red','blue','yello'],
        obj:{
            name:'李华',
            age:18
        }
    }
})

//通过下标替换数据
v.$set(v.arrayData,0,'new Red');
Vue.set(v.arrayData,1,'new Blue')
//通过key添加数据
v.$set(v.obj,'gender',"男")
Vue.set(v.obj,'age','new 18')

组件

组件基本注册

全局组件注册

<div id="app">
    <button-count></button-count>
    <button-count></button-count>
    <button-count></button-count>
</div>
//注册一个叫button-count的按钮
Vue.component("button-count",{
    data:function(){
        return{
            count:0
        }
    },
    //方法一:
    //template:'<button @click="count++">点击了{{count}}次</button>',
    //方法二:
    template:'<button @click="handler">点击了{{count}}次</button>',
    methods:{
        handler:function(){
            this.count += 2;
        }
    }
});
var v = new Vue({
    el:'#app',
    data:{}
});

局部变量

<div id="app">
    <hello-world></hello-world>
    <hello-tom></hello-tom>
</div>
var helloWorld = {
    data:function(){
        return{
            msg:'helloWorld'
        }
    },
    template:'<div>{{msg}}</div>'
}
var helloTom = {
    data:function(){
        return{
            tom:'helloTom'
        }
    },
    template:'<div>{{tom}}</div>'
}
var v = new Vue({
    el:'#app',
    components:{
        "hello-world":helloWorld,
        'hello-tom':helloTom
    }
})

props 用于接收传递过来的值

<div id="app">
    <div>{{parent}}</div>
    <menu-item title="来自父组件的数据"></menu-item>
    <menu-item :title="ptitle" content='hello'></menu-item>
</div>
Vue.component('menu-item',{
    data:function(){
        return{
            msg:'子组件'
        }
    },
    props:['title','content'],
    template:"<div>{{msg +'----'+ title +'----' +content}}</div>"
})
var v = new Vue({
    el:'#app',
    data:{
        parent:'来自父元素的内容',
        ptitle:'动态绑定数据'
    }
})

子组件向父组件传值

无参传值

<div id="app">
    <p :style="{fontSize:fontSize + 'px'}">{{pmsg}}</p>
    <!-- 接收下面的点击事件,执行handler函数 -->
    <menu-item @zoom-size='handler'></menu-item>
</div>
Vue.component('menu-item',{
    //$emit固定格式,$emit 触发父组件的自定义事件,zoom-size在这个地方相当传递了点击事件
   template:`
		<button @click='$emit("zoom-size")'>扩大文字大小</button>
	`
	});
var v = new Vue({
    el:'#app',
    data:{
        pmsg:'父组件的内容',
        fontSize:10
    },
    methods:{
        handler:function(){
            this.fontSize++;
        }
    }
})

有参传值

<div id="app">
    <p :style="{fontSize:fontSize+'px'}">{{pmsg}}</p>
    <menu-item @edit-click='handler($event)'></menu-item>
</div>
Vue.component('menu-item',{
    data:function(){
        return{
            msg:'点击按钮文字变大'
        }
    },
    template:`
<div>
<button @click="$emit('edit-click',5)">{{msg}}</button>
<button @click="$emit('edit-click',10)">{{msg}}</button>
</div>
`
});
var v = new Vue({
    el:'#app',
    data:{
        pmsg:'这是文字',
        fontSize:10,
    },
    methods:{
        handler:function(num){
            this.fontSize += num;
        }
    }
})

兄弟之间的组件传参

var vm = new Vue();
vm.$on('事件名称',参数);//绑定事件
vm.$off('事件名称');//解除绑定事件
vm.$emit('事件名称',参数);//执行事件
<div id="app">
    <p>父组件: 点击tom,jerry数字相加;点击jerry,tom数字相加;</p>
    <button @click='untie'>解除绑定事件</button>
    <tom-test></tom-test>
    <jerry-test></jerry-test>
</div>
//绑定事件中心
var hub = new Vue();
Vue.component('tom-test',{
    data:function(){
        return{
            num:0
        }
    },
    template:`
        <div>
        <p>Tom:{{num}}</p>
        <button @click='handler'>点击</button>
        </div>
	`,
    methods:{
        handler:function(){
            //$emit('函数名称',参数);用于执行事件
            hub.$emit('jerry-event',1)
        }
    },
    mounted:function(){
        //$on('事件名称',执行的函数);用于绑定事件
        hub.$on('tom-event',(val)=>{
            this.num+=val;
        });
    }
});

Vue.component('jerry-test',{
    data:function(){
        return{
            num:0
        }
    },
    template:`
        <div>
        <p>jerry:{{num}}</p>
        <button @click='handler'>点击</button>
        </div>
    `,
    methods:{
        handler:function(){
            hub.$emit('tom-event',2)
        }
    },
    mounted:function(){
        hub.$on('jerry-event',(val)=>{
            this.num+=val;
        });
    }
});
var v = new Vue({
    el:'#app',
    methods:{
        untie:function(){
            //$off('事件名');解除绑定事件
            hub.$off('tom-event')
            hub.$off('jerry-event')
        }
    }
})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值