VUE入门基础笔记

1,首先说明,这篇笔记是参照尚硅谷vue教程视频而来,如有侵权,请联系删除

2,直接上示例

3.1 vue数据绑定

<div id="app">
    <h2>数据绑定</h2>
    <input type="text" v-model="msg"/>
    <p>{{msg}}</p> <!--需要注意的是p标签是不允许使用v-model的-->
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
    const  vm= new Vue({
        el:'#app',//dom元素
        data:{
            msg:''
        }
    })
</script>

3.2强制数据绑定及事件绑定

<body>
<div id="app">
    <!--模版语法-->
    <input type="text" v-model="msg"/>
    <p>{{msg}}</p>
    <p>{{msg.toUpperCase()}}</p>
    <p>{{msg.toLowerCase()}}</p>

    <!--强制数据绑定-->
    <img :src="imgUrl"/><!--可以显示外部网站的图片-->
    <img src="imgUrl"/> <!--这种绑定是无法将数据显示出来的,除非是本服务器内部的数据才会显示-->
    <!--http://localhost:63342/code/VueTest/Vue_Test/js/imgUrl -->

    <!--事件绑定-->
    <button @click="test">click</button>
    <button @click="test()">click</button>
    <button @click="test1(msg)">click</button>

</div>
<script type="text/javascript" src="vue.js"></script>
<script>
    const vm = new Vue({
        el:'#app',
        data:{
            msg:'',
            imgUrl: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=311212150,89993752&fm=26&gp=0.jpg',
            test1(content){ //方法可以写在data里面,也可以写在methods里面
                alert("test2 HELLO")
            }
        },
        methods:{
            test(){
                alert("hello")
            }
        }
    })
</script>
</body>

3.3属性计算及属性监听

<body>
<div id="app">
    姓:<input type="text" placeholder="lastName" v-model="lastName"/>
    名:<input type="text" placeholder="firstName" v-model="firstName"/>
    <br>
    全名:<input type="text" placeholder="fullName1" v-model="fullName1"/>
    <br>
    全名:<input type="text" placeholder="fullName2" v-model="fullName2"/>
    <br>
    全名:<input type="text" placeholder="fullName3" v-model="fullName3"/>
    <p>{{firstName}} - {{lastName}}</p>
    单向:<p>{{fullName1}}</p>
    反向:<p>{{fullName3}}</p>
    双向:<p>{{fullName2}}</p>
</div>
<script type="text/javascript" src="vue.js"></script>
<script>
    const  vm = new Vue({
        el:'#app',
        data:{
            lastName:'',
            firstName:'',
            fullName3:''
        },
        computed:{ //属性计算
            fullName1(){ //使用方法返回数据
                return this.firstName +'-'+ this.lastName
            },
            fullName2:{//使用对象返回,需要设计set,get方法
                set(val){
                   const names= val.split('-');
                    this.firstName= names[0];
                    this.lastName= names[1];
                },
                get(){
                    return this.firstName +'-'+ this.lastName
                }
            }
        },
        watch:{//属性的监视方法一; 对于监听的属性一定需要在data里面定义,否则会出错
            firstName: function(val){//相当于属性的set方法
                this.fullName3 = val +"-" + this.lastName
            }
        }
    })
    //属性监视二
        vm.$watch('lastName',function(val){
            this.fullName3 = this.firstName +"-" + val
        })

</script>
</body>

3.4样式绑定

<style type="text/css">
    .aCLASS{
        color: red;
    }

    .bCLASS{
        color: blue;
    }

    .cCLASS{
        font-size: 100px;
    }

</style>
<body>
<div id="app">
<p :class="aCLASS">classA字符串</p>
<p :class="{aCLASS: hasClassA, bCLASS: hasClassB}">classB对象</p>
<p :class="['aCLASS', 'bCLASS']">classC数组</p>

    <p :style="{color:activeColor, fontSize}">style样式绑定</p>

    <button @click="update">更新变色</button>
</div>
<script type="text/javascript" src="vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            aCLASS:'aCLASS',
            hasClassA: true,
            hasClassB: false,
            activeColor:'red',
            fontSize : '50px'
        },
        methods:{
            update(){
              this.aCLASS='cCLASS';
              this.hasClassA=!this.hasClassA;
              this.hasClassB=!this.hasClassB;
              this.activeColor='green',
              this.fontSize = '20px'
            }
        }
    })
</script>
3.5 v-if 条件渲染
<
body> <div id = "app"> <p v-if="ok">成功</p> <p v-else>失败</p> <p v-show="ok">成功</p> <p v-show='!ok'>失败</p> <button @click="ok=!ok">切换</button> </div> <script type="text/javascript" src="vue.js"></script> <script> new Vue({ el:'#app', data:{ ok:true } }) </script>
3.6 for循环/列表过滤
<body>
<div id="app">
    <input type="text" placeholder="search" v-model="searchName"/>
<h2>列表查询</h2>
    <ul>
        <li v-for="(p,index) in filterPersons" :key="index">
            {{p.id}} -- {{p.name}} -- {{p.age}}
        </li>
    </ul>
    <button @click="setOrderType(1)">升序</button>
    <button @click="setOrderType(-1)">降序</button>
    <button @click="setOrderType(0)">复原</button>
</div>
<script type="text/javascript" src="vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            searchName:'',
            orderType:0,
            persons:[
                {id:1,name:'tom',age:15},
                {id:2,name:'jack',age:14},
                {id:3,name:'bob',age:16},
                {id:4,name:'Mary', age:20}
            ]
        },
        computed:{
            filterPersons(){
            //先取出数据
                const {searchName,persons,orderType} =this;
                let arr=[...persons];
                //过滤数组
                if(searchName.trim())
                {
                    arr=persons.filter(p=>p.name.indexOf(searchName) !== -1)//数组的过滤
                }
                //s数组排序
                if(orderType)
                {
                    arr.sort(function(p1,p2){ //数组的sort方法的重写
                        if(orderType === 1)
                        {
                            return p1.age-p2.age;
                        }else
                        {
                            return p2.age-p1.age;
                        }
                    })
                }
                return arr;
            }
        },
        methods:{
            setOrderType(orderType){
                this.orderType = orderType;
            }
        }
    })
</script>
3.7 事件处理
<body>
<!--
1. 绑定监听:
  v-on:xxx="fun"
  @xxx="fun"
  @xxx="fun(参数)"
  默认事件形参: event
  隐含属性对象: $event
2. 事件修饰符:
  .prevent : 阻止事件的默认行为 event.preventDefault()
  .stop : 停止事件冒泡 event.stopPropagation()
3. 按键修饰符
  .keycode : 操作的是某个keycode值的健
  .enter : 操作的是enter键
-->

<div id="app">
<h2>绑定监听</h2>
    <button @click="test">test1</button>
    <button @click="test2('abc')">test2</button>
    <button @click="test3('abc',$event)">test3</button>

    <h2>2. 事件修饰符</h2>
    <a href="http://www.baidu.com" @click.prevent="test4">百度</a>
    <div style="width: 200px;height: 200px;background: red" @click="test5">
        <div style="width: 100px;height: 100px;background: blue" @click.stop="test6"></div>
    </div>
    <h2>3. 按键修饰符</h2>
    <input type="text" @keyup.13="test7">
    <input type="text" @keyup.enter="test7">
</div>

<script type="text/javascript" src="vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{

        },
        methods:{
            test(){
                alert('test1')
            },
            test2(val){
                alert(val)
            },
            test3(val,event){
                alert(val +"--" + event.target.textContent)
            },
            test4(){
                alert('点击了链接')
            },
            test5(){
                alert('out')
            },
            test6(){
                alert('inner')
            },
            test7 (event) {
                alert(event.target.value)
            }
        }
    })
</script>
3.8 表单数据绑定
<!--
1. 使用v-model(双向数据绑定)自动收集数据 text/textarea checkbox radio select --> <div id="demo"> <form action="/xxx" @submit.prevent="handleSubmit"> <span>用户名: </span> <input type="text" v-model="username"><br> <span>密码: </span> <input type="password" v-model="pwd"><br> <span>性别: </span> <input type="radio" id="female" value="女" v-model="sex"> <label for="female"></label> <input type="radio" id="male" value="男" v-model="sex"> <label for="male"></label><br> <span>爱好: </span> <input type="checkbox" id="basket" value="basket" v-model="likes"> <label for="basket">篮球</label> <input type="checkbox" id="foot" value="foot" v-model="likes"> <label for="foot">足球</label> <input type="checkbox" id="pingpang" value="pingpang" v-model="likes"> <label for="pingpang">乒乓</label><br> <span>城市: </span> <select v-model="cityId"> <option value="">未选择</option> <option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option> </select><br> <span>介绍: </span> <textarea rows="10" v-model="info"></textarea><br><br> <input type="submit" value="注册"> </form> </div> <script type="text/javascript" src="vue.js"></script> <script> new Vue({ el:'#demo', data:{ username:'', pwd:'', sex:'', likes:['foot'], cityId:'2', info:'', allCitys:[{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}] }, methods:{ handleSubmit () { console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info) alert('提交注册的ajax请求') } } }) </script>
3.9 过滤器

<
body> <!-- 1. 理解过滤器 功能: 对要显示的数据进行特定格式化后再显示 注意: 并没有改变原本的数据, 可是产生新的对应的数据 2. 编码 1). 定义过滤器 Vue.filter(filterName, function(value[,arg1,arg2,...]){ // 进行一定的数据处理 return newValue }) 2). 使用过滤器 <div>{{myData | filterName}}</div> <div>{{myData | filterName(arg)}}</div> --> <!--需求: 对当前时间进行指定格式显示--> <div id="test"> <h2>显示格式化的日期时间</h2> <p>{{time}}</p> <p>最完整的: {{time | dateString}}</p> <p>年月日: {{time | dateString('YYYY-MM-DD')}}</p> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script> <script> // 定义过滤器 Vue.filter('dateString', function (value, format='YYYY-MM-DD HH:mm:ss') { return moment(value).format(format); }) new Vue({ el: '#test', data: { time: new Date() }, mounted () {//初始化 setInterval(() => { this.time = new Date() }, 1000) } }) </script>
3.10 指令

<
head> <meta charset="UTF-8"> <title>Title</title> <style> [v-cloak] { display: none } </style> </head> <body> <!-- 常用内置指令 v:text : 更新元素的 textContent v-html : 更新元素的 innerHTML v-if : 如果为true, 当前标签才会输出到页面 v-else: 如果为false, 当前标签才会输出到页面 v-show : 通过控制display样式来控制显示/隐藏 v-for : 遍历数组/对象 v-on : 绑定事件监听, 一般简写为@ v-bind : 强制绑定解析表达式, 可以省略v-bind v-model : 双向数据绑定 ref : 为某个元素注册一个唯一标识, vue对象通过$refs属性访问这个元素对象 v-cloak : 使用它防止闪现表达式, 与css配合: [v-cloak] { display: none } --> <div id="example"> <p v-cloak>{{content}}</p> <p v-text="content"></p> <!--p.textContent = content--> <p v-html="content"></p> <!--p.innerHTML = content--> <p ref="msg">abcd</p> <!--ref唯一标识--> <button @click="hint">提示</button> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript"> new Vue({ el: '#example', data: { content: '<a href="http://www.baidu.com">百度一下</a>' }, methods: { hint () { alert(this.$refs.msg.innerHTML) } } }) </script> </body>
3.11 自定义指令

<!--
1. 注册全局指令 Vue.directive('my-directive', function(el, binding){ el.innerHTML = binding.value.toupperCase() }) 2. 注册局部指令 directives : { 'my-directive' : { bind (el, binding) { el.innerHTML = binding.value.toupperCase() } } } 3. 使用指令 v-my-directive='xxx' --> <!-- 需求: 自定义2个指令 1. 功能类型于v-text, 但转换为全大写 2. 功能类型于v-text, 但转换为全小写 --> <div id="test"> <p v-upper-text="msg"></p> <p v-lower-text="msg"></p> </div> <div id="test2"> <p v-upper-text="msg"></p> <p v-lower-text="msg"></p> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript"> // 注册一个全局指令 // el: 指令所在的标签对象 // binding: 包含指令相关数据的容器对象 Vue.directive('upper-text', function (el, binding) { console.log(el, binding) el.textContent = binding.value.toUpperCase() }) new Vue({ el: '#test', data: { msg: "I Like You" }, // 注册局部指令 directives: { 'lower-text'(el, binding) { console.log(el, binding) el.textContent = binding.value.toLowerCase() } } }) new Vue({ el: '#test2', data: { msg: "I Like You Too" } }) </script>
3.12 插件

<
div id="demo"> <!--使用自定义指令--> <p v-my-directive="msg"></p> </div> </body> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript" src="vue-plugins.js"></script> <script> //使用自定义插件 Vue.use(myPlugin); var vm= new Vue({ el:"#demo", data:{ msg:"atguigu" } }); //调用自定义的静态方法 Vue.MyGlobalMethod(); //调用自定义的对象方法 vm.$myMethod() //----插件 (function(){ const myPlugin={}; myPlugin.install=function (Vue,options) { //1,添加全局方法或属性 Vue.MyGlobalMethod=function(){ alert('vue 函数对象方法执行'); } //2,添加全局资源 Vue.directive('my-directive',function (el,binding) { el.innerHTML='myPlugin my-directive'+binding.value }); //3,添加实例方法 Vue.prototype.$myMethod=function () { alert('vue 示例对象的方法执行'); } } //对外暴露插件 window.myPlugin=myPlugin; })()

猜你喜欢

转载自www.cnblogs.com/pierceming/p/10293304.html
今日推荐