Vue02

Vue案例:

<body>
<div id="app">
    <!--第一部分-->
    <fieldset>
        <legend>info submit</legend>
        <div>
            <span>姓名:</span>
            <input type="text" placeholder="请输入姓名" v-model="newPerson.name">
        </div>
        <div>
            <span>年龄:</span>
            <input type="text" placeholder="请输入年龄"  v-model="newPerson.age">
        </div>
        <div>
            <span>性别:</span>
            <select  v-model="newPerson.sex">
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
        </div>
        <div>
            <span>手机:</span>
            <input type="text" placeholder="请输入手机号码"  v-model="newPerson.phone">
        </div>
        <button @click="createNewPerson()">创建新用户</button>
    </fieldset>
    <!--第二部分-->
    <table>
        <thead>
        <tr>
            <td>姓名</td>
            <td>性别</td>
            <td>年龄</td>
            <td>手机</td>
            <td>删除</td>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(p, index) in persons">
            <td v-text="p.name"></td>
            <td v-text="p.age"></td>
            <td v-text="p.sex"></td>
            <td v-text="p.phone"></td>
            <td>
                <button @click="delPerson(index)">删除</button>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        mounted(){
            // 请求数据
            this.getPersonList();
        },
        data: {
            persons: [],
            newPerson: {name: '', age: 0, sex: '男', phone: ''}
        },
        methods:{
            getPersonList(){
                this.persons = JSON.parse(window.localStorage.getItem('persons') || '');
            },
            createNewPerson(){
                if(this.newPerson.name === ''){
                    alert('name cant be null');
                    return;
                }
                if(this.newPerson.age < 0){
                    alert('please enten your right age');
                    return;
                }
                this.persons.unshift(this.newPerson);
                window.localStorage.setItem('persons',JSON.stringify(this.persons));
                // 清空数据
                this.newPerson = {name: '', age: 0, sex: '男', phone: ''}
            },
            delPerson(index){
                this.persons.splice(index,1);
                window.localStorage.setItem('persons',JSON.stringify(this.persons));
            }
        }
    })
</script>
</body>

localStorage:

  • localStorage生命周期是永久,这意味着除非用户显示在浏览器提供的UI上清除localStorage信息,否则这些信息将永远存在。
  • 存放数据大小为一般为5MB,而且它仅在客户端(即浏览器)中保存,不参与和服务器的通信。

常用API:

  • localStorage.setItem("key","value");
    以“key”为名称存储一个值“value”
  • localStorage.getItem("key");
    获取名称为“key”的值
  • localStorage.removeItem("key");
    删除名称为“key”的信息
  • localStorage.clear();
    清空localStorage中所有信息

一、MVC和MVVM的区别?

1. MVC

M是指业务模型,V是指用户界面,C则是控制器

  • M即model模型,  数据层,负责数据的处理和获取的数据接口层。
  • V即View视图, 视图层, 是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。
  • C即controller控制器, 控制器层,它是 Model 和 View 之间的胶水或者说是中间人。
  • Model和View是完全隔离的,由C作为中间人来负责二者的交互
  • 同时三者是完全独立分开的
  • 这样可以保证M和V的可测试性和复用性,但是一般由于C都是为特别的应用场景下的M和V做中介者,所以很难复用。



MVC的好处:耦合性低、重用性高、部署快,生命周期成本低、可维护性高
存在的问题:不适合小型,中等规模的应用程序、视图与控制器间的过于紧密的连接并且降低了视图对模型数据的访问/


2.MVVM

Model --->每个页面的单独数据
View --->每个页面中的HTML结构
VM ---> 调度者[图片上传中...(image.png-ef8151-1548517314428-0)]

![MVVM](https://upload-images.jianshu.io/upload_images/5017428-3788364b336c811c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

好处:

  • 数据驱动:
    数据驱动

  • VM提供数据的双向绑定
    VM提供数据的双向绑定


二、常见的修饰符

<body>
<div id="app">
    <div class="big-box" @click="bigBoxClick()">
        <div class="box" @click="boxClick()">
            <button @click="btnClick()">按钮</button>
        </div>
    </div>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{},
        methods:{
            bigBoxClick(){
                console.log('点击了大盒子');
            },
            boxClick(){
                console.log('点击了盒子');
            },
            btnClick(){
                console.log('点击了按钮');
            },
            attack(){
                console.log('fire in the hall');
            }

        }
    })
</script>
</body>

这个时候点击 按钮,如下图,时间冒泡了
image.png

1.阻止冒泡:

<div id="app">
    <div class="big-box" @click="bigBoxClick()">
        <div class="box" @click="boxClick()">
            <button @click.stop="btnClick()">按钮</button>
        </div>
    </div>
</div>

image.png

2.事件的捕获

<div id="app">
    <div class="big-box" @click="bigBoxClick()">
        <div class="box" @click.capture="boxClick()">
            <button @click="btnClick()">按钮</button>
        </div>
    </div>
</div>

点击按钮后,先触发 红盒子的事件,然后触发 按钮 事件,最后触发大盒子。
事件捕获

3.self

<div id="app">
    <div class="big-box" @click="bigBoxClick()">
        <div class="box" @click.self="boxClick()">
            <button @click="btnClick()">按钮</button>
        </div>
    </div>
</div>

点击 按钮,触发按钮事件 和 大盒子的事件,红盒子被跳过了
点击按钮

红盒子上的事件在点击了红盒子才会触发
点击红盒子

4.阻止默认事件

<div id="app">
<a href="http://www.baidu.com" @click.prevent="attack()">点击我啊</a>
</div>

阻止默认事件

5.once 事件只触发一次

<div id="app">
    <button @click.once="attack()">click me</button>
</div>

点击按钮,只会 触发一次,第二次点击不会再触发


6. .stop 和 .self 的区别

  • .stop 是真正意义上的阻止冒泡;
  • .self 只会阻止自己身上冒泡行为的触发,并不会真正阻止冒泡的行为。

三、样式类

1. :class

<body>
<div id="app">
    <p :class="['box1']">people change,things go wrong</p>
    <p :class="['box1',isShow ? 'box2 box3':'']">shit happens,life gose on</p>
    <p :class="[{'box1':isShow}]">不说再见</p>
    <p :class="classObj">调整呼吸,下一句让人更加惊艳</p>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            isShow:true,
            classObj:{'box1':false,'box2':false,'box3':true}
        }
    })
</script>
</body>

样式类

2. :style

<body>
<div id="app">
    <p :style="style1">people change,things go wrong</p>
    <p :style="[style1,style2]">shit happens,life gose on</p>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            style1:{color:'red',fontWeight:'bold'},
            style2:{backgroundColor:'blue'}
        }
    });
</script>
</body>

:style

四、ES6知识点

1. ForEach、some、every

ES6中 伪数组转真数组:

forEach
伪数组转成真数组才能遍历

Array.prototype.slice.call(伪数组).forEach(()=>{});


<body>
<div id="app">
    <ul ref="ulParent">
        <li style="height: 60px;">1</li>
        <li style="height: 70px;">2</li>
        <li style="height: 80px;">3</li>
        <li style="height: 90px;">4</li>
        <li style="height: 100px;">5</li>
    </ul>

    <button @click="getAllLiHeight()">获取高度</button>
    <button @click="dealSome()">验证some</button>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#app",
        data:{
            dataArr:['apple','book','blackboard']
        },
        methods:{
            getAllLiHeight(){
                let liHeightArr = [];
                // 1. 获取 DOM 对象
                let allLis = this.$refs.ulParent.getElementsByTagName('li');
                // 2.把 伪数组转换为真数组
                Array.prototype.slice.call(allLis).forEach((li)=>{
                    liHeightArr.push(li.clientHeight);
                });
                console.log(Array.prototype.slice.call(allLis));
                console.log(liHeightArr);
            },
            dealSome(){
                let result = this.dataArr.some(function (str) {
                    return str === 'apple';
                });
                console.log(result);
            }
        }
    })
</script>
</body>

结果:
some 和 伪数组转真数组



some 和 every: 判断数组的所有元素是否满足指定条件,区别在于,
every是一假即假,而some是一真即真。

<script>
    var persons = [
        {name:'Nurato',age:10},
        {name:'LiMing',age:20},
        {name:'Daney',age:30}
    ];
    var every_result = persons.every(function (p) {
        return p.age > 15
    });
    console.log(every_result); //false

    var some_result = persons.some(function (p) {
        return p.age > 21;
    });
    console.log(some_result); // true
</script>


2.filter

<body>
<div id="app">
    <p>{{money}}</p>
    <p>{{money | moneyFormat(money)}}</p>
</div>
<script src="js/vue.js"></script>
<script>
// 定义全局过滤器
Vue.filter('moneyFormat',(money)=>{
    return '¥' + money.toFixed(2);
});

// 1. 创建 Vue 实例
    new Vue({
        el:'#app',
        data:{
            money:236481.12345
        },
        filters:{
            // 局部过滤器
            moneyFormat(money){
                return '$' + money.toFixed(4); // 保留四位小数,四舍五入
            }
        }
    })
</script>
</body>

优先使用局部过滤器,结果:

236481.12345

$236481.1235

3.ES6中的字符串方法

这个方法可以帮你判断一个字符串是否包含另外一个字符串。

str.includes(searchString[, position])

searchString 要在此字符串中搜索的字符串

position 可选。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0。

该方法区分大小写

'Blue Whale'.includes('blue'); // returns false
'Blue Whale'.includes('Blue'); // returns true



五、计算属性

<body>
<div id="app">
    <p>初始值: {{name}}</p>
    <p>翻转:{{name.split('').reverse().join('')}}</p>
    <p>方法:{{reverseStr()}}</p>
    <p>计算属性:{{reverse}}</p>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            name:'hello'
        },
        methods:{
            reverseStr(){
                return this.name.split('').reverse().join('')
            }
        },
        computed:{ //计算选项
                reverse:{
                    get(){
                        return this.name.split('').reverse().join('');
                    }
                }
        }
    })
</script>
</body>

结果:

初始值: hello

翻转:olleh

方法:olleh

计算属性:olleh


<body>
<div id="app">
    <p>{{fullName}}</p>
    <button @click="deal()">调用计算属性中的setter方法</button>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            firstName:'zhang',
            lastName:'san'
        },
        methods:{
            deal(){
                this.fullName = 'Jack chen';
            }
        },
        computed:{
            fullName:{
                get(){
                    return this.firstName + this.lastName;
                },
                set(str){
                    let nameArr = str.split(' ');
                    this.firstName = nameArr[0];
                    this.lastName = nameArr[1];
                }
            }
        }

    });
</script>
</body>

结果: zhangsan , 点击按钮后变为 Jackchen

猜你喜欢

转载自www.cnblogs.com/friday69/p/10353242.html