0
点赞
收藏
分享

微信扫一扫

【Vue全家桶】--- 第一章:Vue核心

_阿瑶 2022-04-20 阅读 32
vue前端

文章目录

Vue技术栈(全家桶)

第一章:Vue核心

1.1、Vue简介

1.1.1、官网

  1. 英文官网: https://vuejs.org/

  2. 中文官网: https://cn.vuejs.org/

1.1.2、介绍与描述

  1. 动态构建用户界面的渐进式 JavaScript 框架

1.1.3、Vue的特点

  1. 遵循 MVVM 模式

  2. 编码简洁, 体积小, 运行效率高, 适合移动/PC 端开发

  3. 它本身只关注UI, 也可以引入其它第三方库开发项目

1.1.4、与其它js框架的关联

  1. 借鉴Angular 的模板数据绑定技术

  2. 借鉴React 的组件化虚拟 DOM 技术

1.1.5、Vue周边库

  1. vue-cli: vue 脚手架

  2. vue-resource

  3. axios

  4. vue-router: 路由

  5. vuex: 状态管理

  6. element-ui: 基于vue 的UI 组件库(PC 端)

​ ……

1.2、初识Vue

关闭生产提示:

<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
</script>  

在这里插入图片描述
在这里插入图片描述

例:

<div id="root">
    <h1>hello,{{name}}</h1>
</div>

<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。

    //创建Vue实例
    const x = new Vue({// const x=  可以省略
        //el:document.getElementById('root');  经典写法
        el: '#root', //el用于指定当前Vue实例为那个容器服务,值通常为css选择器字符串
        //el:'.root'//表示选中class属性
        data: {  //data中用于存储数据,数据供el所指定的容器中使用,值我们暂时先写成一个对象
            name: '小王'
        }
    });
</script>

1.3、模板语法

1.3.1、效果

<div class="root">
    <h1>插值语法</h1>
    <h3>你好,{{name}}</h3>
    <hr/>
    <h1>指令语法:</h1>
    <a v-bind:href="url">点我去尚硅谷学习1</a>
    <a :href="school.url" >点我去尚硅谷学习2</a>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。

    //创建Vue实例
    const x = new Vue({// const x=  可以省略
        //el:document.getElementById('root');  经典写法
        el: '.root', //el用于指定当前Vue实例为那个容器服务,值通常为css选择器字符串
        //el:'.root'//表示选中class属性
        data: {  //data中用于存储数据,数据供el所指定的容器中使用,值我们暂时先写成一个对象
            name: '小王Hello',
            url:'http://www.atguigu.com',
            school:{
                url:'http://www.atguigu.com'
            }
        }
    });
</script>

在这里插入图片描述

1.3.2、模板的理解

html 中包含了一些JS 语法代码,语法分为两种,分别为:

  1. 插值语法(双大括号表达式)

  2. 指令(以v-开头)

1.3.3、插值语法

  1. 功能: 用于解析标签体内容

  2. 语法: {{xxx}} ,xxxx 会作为js 表达式解析

1.3.4、指令语法

1.功能: 解析标签属性、解析标签体内容、绑定事件

  1. 举例:v-bind:href=“xxx” 或简写成 :href=“xxx” ,xxx同样要写成js表达式

    且可以直接读取到data中的所有属性

  2. 说明:Vue中有很多指令,却形式都是v-???,此处我们只使用的是v-bind举个例子

1.4、数据绑定

分为 单向数据绑定、双向数据绑定

1.4.1、效果

<!-- 普通写法 -->
单向数据的绑定:<input type="text" v-bind:value="name"><br>
双向数据的绑定:<input type="text" v-model:value="name"><br>
<!-- 简写 -->
单向数据的绑定:<input type="text" :value="name"><br>
双向数据的绑定:<input type="text" v-model="name">
<!--如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上  -->
<!-- <h2 v-model:x="name">你好</h2> -->
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            name: '小王'
        }
    });
</script>

在这里插入图片描述

1.4.2、单向数据绑定

  1. 语法:v-bind:href =“xxx” 或简写为 :href

  2. 特点:数据只能从data 流向页面

1.4.3、双向数据绑定

  1. 语法:v-mode:value=“xxx” 或简写为 v-model=“xxx”,因为v-model默认收集的是value的值

  2. 特点:数据不仅能从data 流向页面,还能从页面流向 data,双向绑定一般都应用在表单元素上(如:input、select等)

1.4.4、datael的两种写法

el

//el的两种写法:
//        第一种常规 可以写成 new Vue({})
//        第二种使用v.$mount("#xxx");
const v =  new Vue({
    //el: '#root',
    data: {
        name: '小王'
    },
    success: (result) => {
        console.log('方法名 success', result);
    }
});
v.$mount("#root");//第二种写法 

data

//data的两种写法:
//     第一种:对象式
//     第二种:函数式  简化写法 data(){}
new Vue({
    el: '#root',
    //data的第一种写法:对象式
    /*  data: {

             }, */
    //data 的第二种写法:函数式 简化写法 data(){}
    data: function () {
        //console.log("@@@",this);
        return {
            name: '小王'
        }
    }
});

1.5、MVVM模型

  1. M:模型(Model) :对应data 中的数据

  2. V:视图(View) :模板

  3. VM:视图模型(ViewModel) : Vue 实例对象

在这里插入图片描述

在这里插入图片描述

1.6、数据代理

Object.defineProperty

在这里插入图片描述

例:

<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
let number = 18;
let person = {
    name: '小王',
    sex: '男'
}
Object.defineProperty(person, 'age', {

    // value: 18,
    // enumerable: true, //控制属性是否可以枚举,默认值是false
    // writable:true, //控制器属性是否可以被修改,默认值是false
    // configurable:true//控制器属性是否可以被删除,默认值是false

    //当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值
    get: function () {
        console.log("有人读取数据");
        return number
    },

    //当有人修改person的age属性时,gset函数(setter)就会被调用,且会收到修改的具体值
    set(value){
        console.log("有人修改了age属性,且值是:",value);
        number = value;
    }
});
console.log(person);
console.log(Object.keys(person));
/* for (const key in person) {
            console.log("@@@", person[key]);
        } */
</script>

1.7、事件处理

1.7.1、基本使用

事例:点击事件

<div id="root">
    <h1>欢迎来到{{name}}学习</h1>
    <button v-on:click="showInfo1">点我提示信息1:不传参</button>
    <button @click="showInfo2(66,$event)">点我提示信息2:传参</button>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。

    const vm = new Vue({
        el: '#root',
        data: {
            name: '尚硅谷'
        },
        methods: {
            //不传参
            showInfo1(event) {
                console.log(event.target.innerText);
                console.log(this);
                alert("同学你好")
            },
            //传参
            showInfo2(number,a) {
                // console.log(event.target.innerText);
                // console.log(this);
                console.log(number,a);
                alert("同学你好!!")
            }
        }
    });
</script>

1.7.2、绑定监听

  1. v-on:xxx=“fun” (fun)方法名

  2. @xxx=“fun”

  3. @xxx=“fun(参数)”

  4. 默认事件形参: event

  5. 隐含属性对象: $event

1.7.3、事件修饰符

常规方式@click="xxx"

Vue方式@click.stop="xxx"

​ xxx:方法名 .stop:阻止事件冒泡的事件修饰符

Vue中的事件修饰符:

1.prevent:阻止默认事件(常用)

​ 例:@click.prevent="xxx"

​ 常规:@click=“xxx” e.preventDefault();//阻止默认行为

2.stop:阻止事件冒泡(常用)

​ 例:@click.stop="xxx"

​ 常规:@click=“xxx” e.stopPropagation();//阻止事件冒泡

3.once:事件只触发一次(常用)

​ 4.capture:使用事件的捕获模式

​ 5.self:只有event.target是当前操作的元素时才触发事件

​ 6.passive:事件默认行为立即执行,无需等待事件回调执行完毕

联合使用:

​ 例:@click.prevent.stop="xxx"

​ 表示先阻止默认行为,再阻止事件冒泡

例:

<div id="root">
    <h1>欢迎来到{{name}}学习</h1>
    <a href="http://www.atguigu.com" @click="showInfo">点击提示信息</a><br>
    <!--  1.prevent:阻止默认事件(常用) -->
    <a href="http://www.atguigu.com" @click.prevent="showInfo">prevent:阻止默认事件(常用)</a><br>

    <!-- 2.stop:阻止事件冒泡(常用) -->
    <div class="demo1" @click="showInfo">
        <button @click.stop="showInfo">stop:阻止事件冒泡(常用)</button>
    </div>

    <!-- 3.once:事件只触发一次(常用) -->
    <button @click.once="showInfo">once:事件只触发一次(常用)</button>

    <!--  4.capture:使用事件的捕获模式 -->
    <!--
捕获阶段:由外到内 
冒泡阶段:由内到外
-->
    <div class="box1" @click.capture="showMsg(1)">
        div1
        <div class="box2" @click="showMsg(2)">
            div2
        </div>
    </div>

    <!-- 5.self:只有event.target是当前操作的元素时才触发事件 -->
    <div class="demo1" @click.self="showInfo">
        <button @click="showInfo">self:只有event.target是当前操作的元素时才触发事件</button>
    </div>

    <!-- 6.passive:事件默认行为立即执行,无需等待事件回调执行完毕 -->
    <!-- 
@scroll:滚动条的滚动
@wheel:鼠标滚动轮,可以一直触发

平板手机常使用passive
-->
    <ul @wheel.passive="demo" class="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>

</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。

    const vm = new Vue({
        el: '#root',
        data: {
            name: '尚硅谷'
        },
        methods: {
            showInfo(e) {
                //e.preventDefault();//阻止默认行为
                //e.stopPropagation();//阻止事件冒泡
                alert("同学你好");
                // console.log(e.target);
            },
            showMsg(msg) {
                console.log("同学你好" + msg)
            },
            demo(msg) {
                for (let index = 0; index < 1000; index++) {
                    console.log("#");

                }
                console.log("累坏了");
            }
        }
    });
</script>

1.7.4、键盘事件

键盘事件:

@keydown:按下即触发

@keyup:按下松手触发

常规方式:使用键盘的keycode值

​ @keydown=“showInfo” 通过 if(e.keyCode!=13)来进行判断

​ 此时为”Enter”事件,

例:

<!-- 准备一个容器 -->
<div id="root">
    <h1>欢迎来到{{name}}学习</h1> 
    <!--
键盘事件
@keydown:按下即触发
@keyup:按下松手触发
-->
    <input type="text" placeholder="按下回车提示输入" @keydown.huiche="showInfo">
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    Vue.config.keyCodes.huiche = 13; //定义可一个别名按键
    const vm = new Vue({
        el: '#root',
        data: {
            name: '尚硅谷'
        },
        methods: {
            showInfo(e) {
                // console.log(e.keyCode);//键盘上对应的code值
                /*   if(e.keyCode!=13){
                          return
                      } */
                //第二种方式:@keyup.enter
                //console.log(e.target.value);
                console.log(e.key)
            }
        }

    });
</script>

1.8、计算属性监视

1.8.1、效果

问题:通过输入”姓”和”名”来组合成为”全名”

要求:”全名”是”姓”-”名” 实现动态变化

在这里插入图片描述

方式一:插值语法实现

<div id="root">
    性: <input type="text" v-model="firstName"><br><br>
    名: <input type="text" v-model="lastName"><br><br>
    <!--firstName.slice(0,3)  表示收集数据的前三位,但需求过多时,不便于观察  -->
    姓名: <span>{{firstName.slice(0,3)}}-{{lastName}}</span>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    new Vue({
        el:'#root',
        data: {
            firstName:'张',
            lastName:'三'
        }
    });
</script>

方式二:methods实现

<div id="root">
    性: <input type="text" v-model="firstName"><br><br>
    名: <input type="text" v-model="lastName"><br><br>
    姓名: <span>{{fullName()}}</span>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    new Vue({
        el:'#root',
        data: {
            firstName:'张',
            lastName:'三'
        },
        methods:{
            fullName(){
                return this.firstName+'-'+this.lastName
            }
        }

    });
</script>

方式三:计算属性实现

1.8.2、计算属性-computed

描述:

原理及优势:

普通写法与简写

普通写法:xxx方法名

computed:{
    xxx:{
        get(){
           return ....操作....
        },
        set(value){
        }
}

简写:xxx方法名

注意要点:

computed: {
    /*  xxx: function () {
                  return  .....
                } */
    xxx() {
        return .....
    }
}

例:

<div id="root">
    性: <input type="text" v-model="firstName"><br><br>
    名: <input type="text" v-model="lastName"><br><br>
    姓名: <span>{{fullName}}</span><br><br>  //后面再有{{fullName}} 也是读取一遍,methods会反复取
    <!--  姓名: <span>{{fullName}}</span><br><br> -->
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm =  new Vue({
        el:'#root',
        data: {
            firstName:'张',
            lastName:'三'
        },
        //计算属性 拥有缓存,读取一次,然后从缓存中读取
        computed:{
            fullName:{
                //get 有什么作用?当有人读取fullName是,get就会被调用,且返回值作为fullName的值
                //get 什么时候被调用?1.初次读取fullName时  2.所依赖的数据发生改变时
                get(){
                    //console.log(this)  此处的this是vm
                    return this.firstName+'-'+this.lastName

                },
                //set 什么时候调用? 当fullName被修改时
                set(value){
                    console.log(value)
                    const arr = value.split('-')
                    this.firstName = arr[0]
                    this.lastName = arr[1]
                }
            }
        }

    });
</script>

1.8.3、监视属性-watch

两种监视写法的简写模式:

**注意:**简写方式不能配置其中的属性。

如:immediate:true,//初始化时让handler调用一下

deep:true,//深度监视开启

例子:通过button的点击事件,来改变”文字”

比如:”今天天气很凉爽” 点击后===》”今天天气很炎热”

在这里插入图片描述

方式一:使用computed计算属性值+methods点击事件

<div id="root">
    <!-- <h2>今天天气很{{isHot?'炎热':'凉爽'}}</h2> -->
    <h2>今天天气很{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
    <!-- 
绑定事件的时候;@xxx ="yyy" yyy可以写一写简单的语句

-->
    <!--  <button @click="isHot = !isHot">切换天气</button> -->
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm =  new Vue({
        el:'#root',
        data: {
            isHot:true
        },
        //计算属性
        computed:{
            info(){
                return this.isHot?'炎热':'凉爽'
            }
        },
        //方法
        methods: {
            changeWeather(){
                this.isHot = !this.isHot
            }
        },

    });

</script>

方式二:监视属性watch

:监视的两种写法

<div id="root">
    <h2>今天天气很{{info}}</h2>
    <button @click="changeWeather">切换天气</button>

</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot
            }
        },
        //第一种方式
        /* watch:{
                isHot:{// 还可监视computed中的info方法
                    immediate:true,//初始化时让handler调用一下
                    //handler什么时候被调用?当isHot发生改变时
                    handler(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue)
                    }
                }
            } */

    });
    //第二种方式
    vm.$watch('isHot', {
        immediate: true,//初始化时让handler调用一下
        //handler什么时候被调用?当isHot发生改变时
        handler(newValue, oldValue) {
            console.log("isHot被修改了", newValue, oldValue)
        }
    })
</script>

1.8.4、深度监视

例:

  • 监视多级结构中的某个属性的变化
  • 监视多级结构中所有属性的变化
<div id="root">
    <h2>今天天气很{{info}}</h2>
    <button @click="changeWeather">切换天气</button>
    <hr>
    <h3>a的值时:{{numbers.a}}</h3>
    <button @click="numbers.a++">点我让a+1</button>
    <hr>
    <h3>a的值时:{{numbers.b}}</h3>
    <button @click="numbers.b++">点我让b+1</button>
    <button @click="numbers={a:666,b:888}">彻底替换掉numbers</button>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true,
            numbers:{
                a:1,
                b:1 
            }
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot
            }
        },
        watch:{

            //监视多级结构中的某个属性的变化
            /*  'numbers.a':{
                    handler(){
                        console.log("a被改变了")
                    }

                } */
            //监视多级结构中所有属性的变化
            numbers:{
                deep:true,//深度监视开启
                handler(){
                    console.log("numbers改变了")
                }
            }
        }

    });

</script>

1.8.5、计算属性与监视区别

例:实现1.8.1节的姓名案例

需求增加:在输入姓的时候,全名延迟一秒实现,此时只能使用watch监视实现

watch监视实现

<div id="root">
    性: <input type="text" v-model="firstName"><br><br>
    名: <input type="text" v-model="lastName"><br><br>
    姓名: <span>{{fullName}}</span><br><br>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
            fullName:'张-三'//此处比计算属性多个fullName
        },
        watch:{
            firstName(newValue){ 
                //延迟一秒
                setTimeout(() => {
                    this.fullName = newValue+'-'+this.lastName 
                }, 1000);
            },
            lastName(newValue){
                this.fullName = this.firstName+'-'+newValue
            }
        }

    });
</script>

1.9、classstyle绑定

1.9.1、理解

  1. 在应用界面中, 某个(些)元素的样式是变化的

  2. class/style 绑定就是专门用来实现动态样式效果的技术

1.9.2、class绑定

1.9.3、style绑定

1.10、条件渲染

1.10.1、条件渲染指令

  1. v-if 与v-else-if、v-else

  2. v-show

1.10.2、比较v-ifv-show

注意:template与只能和if的配合使用

<!-- template与if的配合使用 -->
<template v-if="n===1">
    <h2 >你好</h2>
    <h2 >平顶山</h2>
    <h2 >小王</h2>
</template>

1.11、列表渲染

在这里插入图片描述

1.11.1、列表显示指令

代码事例:

<div id="root">
    <!-- 1.遍历数组 -->
    <h2>人员列表</h2>
    <ul>
        <!-- 
1.in 可以换成of 
2.v-for="(p,index) in persons" :key="index"
或v-for="p in persons" :key="p.id"
-->
        <li v-for="(p,index) in persons" :key="index">
            {{p.name}}-{{p.age}}--{{index}}
        </li>
    </ul>

    <!-- 2.遍历对象 -->
    <h2>汽车信息</h2>
    <ul>

        <li v-for="(value,k) in car" :key="k" >
            {{k}}--{{value}}
        </li>
    </ul>

    <!-- 3.遍历字符串(用的少) -->
    <h2>遍历字符串</h2>
    <ul>

        <li v-for="(char,index) in str" :key="index" >
            {{char}}--{{index}}
        </li>
    </ul>

    <!-- 4.遍历指定次数(用的少) -->
    <h2>遍历指定次数</h2>
    <ul>

        <li v-for="(number,index) in 5" :key="index">
            {{number}}--{{index}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            persons: [
                { id: '001', name: '张三', age: 10 },
                { id: '002', name: '李四', age: 12 },
                { id: '003', name: '王五', age: 13 }
            ],
            str:'hello',
            car: {
                name: '奥迪',
                price: '80w',
                color: '黑色'
            }
        }
    });
</script>

1.11.2、面试题:key实现原理

遍历列表时key的作用(index作为key)

在这里插入图片描述

遍历列表时key的作用(id作为key)

在这里插入图片描述

1.11.3、列表过滤

在这里插入图片描述

两种实现方式:使用watch实现、使用computed实现

<!-- 准备好一个容器 -->
<!-- div#root -->
<div id="root">
    <!-- 遍历数组 -->
    <h2>人员列表</h2>
    <input type="text" placeholder="请输入名字" v-model="keyWord">
    <ul>
        <li v-for="(p,index) in filPersons" :key="index">
            {{p.name}}-{{p.age}}--{{index}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    //使用watch实现
    /*  new Vue({
             el: '#root',
             data: {
                 keyWord: '',
                 persons: [
                     { id: '001', name: '马冬梅', age: 19, sex: '女' },
                     { id: '002', name: '周冬雨', age: 20, sex: '女' },
                     { id: '003', name: '周杰伦', age: 21, sex: '男' },
                     { id: '004', name: '温兆伦', age: 22, sex: '男' }
                 ],
                 filPersons: []
             },
             watch: {
                 keyWord: {
                     immediate:true,
                     handler(value) {
                         this.filPersons = this.persons.filter((p) => {
                             return p.name.indexOf(value) !== -1//判断是否包含,不包含则返回-1
                         })
                     }
                 }
             }
         }); */

    //用computed,优先使用
    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            sortType: 0,//0代表原顺序,1代表降序,2代表升序 @click=""
            persons: [
                { id: '001', name: '马冬梅', age: 20, sex: '女' },
                { id: '002', name: '周冬雨', age: 19, sex: '女' },
                { id: '003', name: '周杰伦', age: 18, sex: '男' },
                { id: '004', name: '温兆伦', age: 22, sex: '男' }
            ]
        },
        computed: {
            filPersons() {
                const arr = this.persons.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                })
                //判断一下是否需要排序
                if (this.sortType) {
                    arr.sort((p1, p2) => {
                        return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
                    })
                    console.log(arr)
                }
                return arr
            }
        }
    });
</script>

1.11.4、Vue监视data中所有的层次的数据

例:

在这里插入图片描述

<div id="root">
    <h1>学生信息</h1>

    <button @click="student.age++">年龄+1岁</button><br/>
    <button @click="addSex">添加性别属性,默认值:男</button><br/>
    <button @click="student.sex = '未知'">修改性别</button><br/>
    <button @click="addFriend">在列表首位添加一个朋友</button><br/>
    <button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button><br/>
    <button @click="addHobby">添加一个爱好</button><br/>
    <button @click="updateHobby">修改第一个爱好为:开车</button><br/>
    <button @click="removeSmoke">过滤掉爱好中的抽烟</button><br/>


    <h3>姓名:{{student.name}}</h3>
    <h3>年龄:{{student.age}}</h3>
    <h3 v-if="student.sex">性别:{{student.sex}}</h3>
    <h3>爱好:</h3>
    <ul>
        <li v-for="(h,index) in student.hobby" :key="index">
            {{h}}
        </li>
    </ul>
    <h3>朋友们:</h3>
    <ul>
        <li v-for="(f,index) in student.friends" :key="index">
            {{f.name}}--{{f.age}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。

    new Vue({
        el:'#root',
        data: {
            student: {
                name: '小王',
                age: 15,
                hobby: ['抽烟', '烫头', '喝酒'],
                friends: [
                    {name:'jerry',age:45},
                    {name:'tony',age:20}
                ]
            },
        },
        methods: {
            addSex(){
                //Vue.set(this.student,'sex',"男")
                this.$set(this.student,'sex',"男")
            },
            addFriend(){
                this.student.friends.unshift({name:'jack',age:44})
            },
            updateFirstFriendName(){
                this.student.friends[0].name = '张三'
            },
            addHobby(){
                this.student.hobby.push('学习')
            },
            updateHobby(){
                //this.student.hobby.splice(0,1,'开车')
                //Vue.set(this.student.hobby,0,'开车')
                this.$set(this.student.hobby,0,'开车')
            },
            removeSmoke(){
                this.student.hobby= this.student.hobby.filter((h)=>{
                    //函数体
                    return h!=='抽烟'
                })
            }
        },
    });

</script>

1.12、收集表单数据

例:

在这里插入图片描述

<div id="root">
    <form @submit.prevent="demo">
        <label for="account">账号:</label>
        <input id="account" type="text" v-model.trim="userInfo.account"><br /><br />
        <label for="pwd">密码:</label>
        <input id="pwd" type="text" v-model.trim="userInfo.pwd"><br /><br />
        年龄:<input type="number" v-model.number="userInfo.age"><br /><br />
        性别:男<input type="radio" name="sex" v-model="userInfo.sex" value="male"><input type="radio" name="sex" v-model="userInfo.sex" value="female"><br /><br />
        爱好:
        学习<input type="checkbox" v-model="userInfo.hobby" value="study">
        打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">
        吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat"><br /><br />
        所属校区:
        <select v-model="userInfo.city">
            <option value="">请选择校区</option>
            <option value="beijing">北京</option>
            <option value="shanghai">上海</option>
            <option value="shenzhen">深圳</option>
            <option value="wuhan">武汉</option>
        </select><br /><br />
        其他信息:
        <textarea v-model.lazy="userInfo.other"></textarea><br /><br />
        <input type="checkbox" v-model="userInfo.agree"> 阅读并接受<a href="http://www.baidu.com">《用户协议》</a>
        <button>提交</button>
    </form>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            userInfo: {
                account: '',
                pwd: '',
                age:'',
                sex: 'female',
                hobby: [],
                city: '',
                other: '',
                agree: ''
            }

        },
        methods: {
            demo() {

            }
        },
    });


</script>

1.13、过滤器

例:

在这里插入图片描述

<div id="root">
    <h2>显示格式后的数据</h2>
    <!-- 计算属性实现 -->
    <h3>现在是:{{fmtTime}}</h3>
    <!-- methods实现 -->
    <h3>现在是:{{getFmtTime()}}</h3>
    <!-- 过滤器实现 -->
    <h3>现在是:{{time | timeformater}}</h3>

    <!-- 过滤器实现(传参) -->
    <h3>现在是:{{time | timeformater('YYYY-MM-DD') | mySlice}}</h3>

    <!-- v-band -->
    <h3 :x="msg | mySlice">xiaowang</h3>
</div>
<div id="root2">
    <h2>{{msg | mySlice}}</h2>
</div>
<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    //全局过滤器(filter),必须定义在Vue之前,一次只能定义一个
    Vue.filter('mySlice',function(value){
        return value.slice(0, 4)
    })
    new Vue({
        el: '#root',
        data: {
            time: Date.now(),
            msg:'你好,小王'

        },
        computed: {
            fmtTime() {
                return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')
            }
        },
        methods: {
            getFmtTime() {
                return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss')

            }
        },
        //局部过滤器
        filters: {//如果传str,则使用传入的值,如果没有传入则使用str="YYYY-MM-DD HH:mm:ss"
            timeformater(value, str = "YYYY-MM-DD HH:mm:ss") {

                return dayjs(value).format(str)

            }/* ,
                    mySlice(value) {

                        return value.slice(0, 4)

                    } */
        }
    })
    new Vue({
        el: '#root2',
        data: {
            msg:'hello,小王'
        }
    });

</script>

1.14、内置指令自定义指令

1.14.1、常用内置指令

前面学过的指令:

8.v-text指令:

9.v-html指令:

10.v-cloak指令(没有值):

11.v-once指令:

12.v-pre指令:

1.14.2、自定义指令

1、定义语法

局部指令:

new Vue ({                            
    directives:{指令名:配置对象} })new Vue({
    directives:{指令名:回调函数} })

全局指令:

Vue.directive(指令名,配置对象)Vue.directive(指令名,回调函数)

2、配置对象中常用的三个回调

3、注意

例:

需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍

需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其绑定的input元素默认获取焦点

<div id="root">
    <h2>{{name}}</h2>
    <h2>当前的n值是:<span v-text="n"></span></h2>
    <h2>放大10背后的n值是:<span v-big="n"></span></h2>
    <button @click="n++">点我n+1</button>

    <hr />
    <input v-fbind:value="n" type="text">

</div>

<script type="text/javascript">
    Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
    //定义全局指令
    Vue.directive('fbind', {
        //指令与元素成功绑定时(一上来)
        bind(element, binding) {
            element.value = binding.value

        },
        //指令所在元素被插入页面时
        inserted(element, binding) {
            element.focus()
        },
        //指令所在的模板被重新解析时
        update(element, binding) {
            element.value = binding.value
        }
    })
    new Vue({
        el: '#root',
        data: {
            n: 1,
            name: '小王'
        },
        directives: {
            /*  big 函数何时会被调用?
                element:DOM元素,binding:绑定的所有信息
                      1. 指令与元素成功绑定时(一上来)
                      2. 指令所在的模板被重新解析时

                */
            big(element, binding) {
                element.innerText = binding.value * 10
            },
            /*   fbind:{
                      //指令与元素成功绑定时(一上来)
                      bind(element,binding){
                          element.value = binding.value

                      },
                      //指令所在元素被插入页面时
                      inserted(element,binding){
                          element.focus()
                      },
                      //指令所在的模板被重新解析时
                      update(element,binding){
                       element.value = binding.value

                      }
                  } */
        }
    });

</script>

1.15、Vue实例生命周期

1.15.1、生命周期流程图

在这里插入图片描述

1.15.2、Vue生命周期分析

1.初始化显示

beforeCreate()

created()

beforeMount()

mounted()

2.更新状态: this.xxx = value

beforeUpdate()

updated()

3.销毁vue 实例: vm.$destory()

beforeDestory()

destoryed()

1.15.3、常用的生命周期方法

1.15.4、销毁Vue实例

举报

相关推荐

0 条评论