(Day65,66) Vue base, instructions, examples member, JS this supplementary functions, bubble sort

A, Vue basis

(A) What is the Vue

  1. JavaScript can be completed independently progressive frame front and rear ends of the split web projects

(B) Why study Vue

  1. Three major frameworks: Angular, React, Vue
  2. Advanced front-end design mode: MVVM
  3. The server can be completely disengaged, so as to render the front end of the code reuse entire page: Component Exploitation
  4. Features: single-page web application, data-driven thinking, two-way data binding, virtual DOM, component-based development

(C) how to use Vue

  1. Vue official website to download the file vue.js
  2. Introduced by the script tag
  3. Mounting on Vue example by el

Two, Vue instruction

(A) text instruction

  1. Interpolation expression: {{ }}, template-based syntax of html
  2. v-next: replacing the contents within the tag, will not parse html code
  3. v-html: replace the contents of the tag is parsed html code
  4. v-once: the controlled label can only be assigned once
<div id="app">
    <!--插值表达式-->
    <p>{{ msg }}</p>
    
    <!--v-next-->
    <p v-next="msg"></p>
    
    <!--v-html-->
    <p v-html="msg"></p>
    
    <!--v-once-->
    <p v-once>{{ msg }}</p>
</div>
<script>
    new Vue({
        el:"#app",
        data:{},
    })
</script>

(B) instruction v-on event

  1. grammar:v-on:事件名='方法变量'
  2. Shorthand:@事件名='方法变量'
  3. Methods variable without parentheses, the default incoming event object ($ event)
  4. Variable method to add parentheses represents the custom parameter passing, the system does not pass the event object, but you can manually incoming
 <div id="app">
        <p v-on:click="f1">{{ msg }}</p>
        <p @click="f1">{{ msg }}</p>
        <p @mouseover="f2" @mouseout="f3" @mouseup="f5" @mousemove="f6" @contextmenu="f7">{{ action }}</p>
        <hr>

        <!-- 事件变量,不添加(),默认会传事件对象: $event -->
        <!-- 事件变量,添加(),代表要自定义传参,系统不再传入事件对象,但是可以手动传入事件对象 -->
        <p @click="f8($event, '第一个')">{{ info }}</p>
        <p @click="f8($event, '第二个')">{{ info }}</p>
    </div>
</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            msg: '点击切换',
            action: '鼠标事件',
            info: '确定点击者'
        },
        methods: {
            f1 () {
                this.msg = '点击了'
            },
            f2 () {
                this.action = '悬浮';
                console.log('悬浮')
            },
            f3 () {
                this.action = '离开'
            },
            f4 () {
                this.action = '按下'
            },
            f5 () {
                this.action = '抬起'
            },
            f6 () {
                this.action = '移动';
                console.log('移动')
            },
            f7 () {
                this.action = '右键';
            },
            f8 (ev, argv) {
                console.log(ev, argv);
                this.info = argv + '点击了';
            }
        }
    })
</script>

(Iii) v-bind attribute command

  1. grammar:v-bind:属性名='变量'
  2. Shorthand::属性名='变量'
  • class attribute binding
    1. Direct Binding
    2. []: Bind multiple class names
    3. '': Content within the quotation marks is constant
    4. {}: Class name status, control class name is in effect
  • style attribute binding
    1. Direct binding:<p :style="myStyle">样式属性</p>
    2. Customized binding: `<p :style="{width: w,height: h, backgroundColor: bgc}">样式属性</p>
  • Html Vue in the background-color css style formed hump variant thereof to be used backgroundColor
<!--绑定全局自定义属性-->
<P v-bind:abc="abc"></P>
<!--直接以原来字符串形式绑定属性,即为一个常量-->
<p v-bind:title=" 'abc' "></p>

<!--单类名绑定-->
<p :class = "c1"></p>
<!--多类名绑定-->
<p :class = "[c2,c3]"></p>
<!--类名状态绑定 var指代可以为一个变量,可以在Vue实例中实时控制其类是否生效-->
<p :class = "{c4:true|false|var}"></p>

<!--样式绑定-->
<div :style:"div_style"></div>
<div :style:"{width:w, height:h, backgroudColor:bc}"></div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        c1:'p1',
        c2:'p2',
        c3:'p3',
        
        div_style:{
            width:"100px",
            height:"100px",
            backgroundColor:"red"
        }
        
        w:"100px",
        h:"100px",
        bc:"red"
        
    })
</script>

(Iv) Form command v-model

  1. Syntax: v-model="变量", value variable values associated with a form tag
  2. V-model variable value can bind bidirectional data, the value of variable bindings can affect the value of the tag form, it will also affect the value of the bound form by tag
  3. When the check box to group name, variable bindings stored value is a value of the radio buttons
  4. When a single box storage of variable bindings is true | false, or customize the replacement value
  5. Multi-box, multi-variable bindings check box is selected value in the array to store the value
<div id="app">
    <!-- v-model针对于表单元素 -->
    <form action="" method="get">
        <!-- 1、双向绑定:服务于文本输入框 -->
        <!-- v-model存储的值为输入框的value值 -->
        <div>
            <input type="text" name="usr" v-model="in_val">
            <input type="password" name="ps" v-model="in_val" >
            <textarea name="info" v-model="in_val"></textarea>
        </div>

        <!-- 2、单选框 -->
        <div>
            <!-- 单选框是以name进行分组,同组中只能发生单选 -->
            <!-- v-model存储的值为单选框的value值 -->
            男:<input type="radio" name="sex" value="男" v-model="ra_val">
            女:<input type="radio" name="sex" value="女" v-model="ra_val">
            {{ ra_val }}
        </div>

        <!-- 3、单一复选框 -->
        <!-- v-model存储的值为true|false -->
        <!-- 或者为自定义替换的值 -->
        <div>
            <input type="checkbox" v-model='sin_val' true-value="选中" false-value="未选中" />
            {{ sin_val }}
        </div>

        <!-- 4、多复选框 -->
        <!-- v-model存储的值为存储值多复选框value的数组 -->
        <div>
            <input type="checkbox" value="喜好男的" name="cless" v-model='more_val' />
            <input type="checkbox" value="喜好女的" name="cless" v-model='more_val' />
            <input type="checkbox" value="不挑" name="cless" v-model='more_val' />
            {{ more_val }}
        </div>
    </form>
</div>

<script type="text/javascript">
    new Vue({
        el: '#app',
        data: {
            in_val: '',
            // 默认值可以决定单选框默认选项
            ra_val: '男',
            // 默认值为true,单一复选框为选中,反之false为不选中
            sin_val: '',
            // 数组中存在的值对应的复选框默认为选中状态
            more_val: ['喜好女的','不挑']
        }
    })
</script>

(E) v-if conditional instructions

  1. v-show="布尔变量": Boolean variable is false, hide the label, hidden way through style="display:none"implementation, use less

  2. v-if="布尔变量": Boolean variable is false, hide the label, do not hide the way for the direct rendering from data security, it is recommended to use

    • v-if="布尔变量"
    • v-else-if="布尔变量"
    • v-else
<div id="app" v-cloak>
    <!--条件指令:
        v-show="布尔变量"   隐藏时,采用display:none进行渲染
        v-if="布尔变量"     隐藏时,不再页面中渲染(保证不渲染的数据泄露)
        -----------------------------
        v-if | v-else-if | v-else
    -->
    <div class="box r" v-show="is_show"></div>
    <div class="box b" v-if="is_show"></div>
    <div class="wrap">
        <button @click="page='r_page'" :class="{active: page==='r_page'}">红</button>
        <button @click="page='b_page'" :class="{active: page==='b_page'}">蓝</button>
        <button @click="page='g_page'" :class="{active: page==='g_page'}">绿</button>
        
        <div class="box r" v-if="page === 'r_page'"></div>
        <div class="box b" v-else-if="page === 'b_page'">11</div>
        <div class="box g" v-else></div>
    </div>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            is_show: false,
            page: 'r_page'
        }
    })
</script>
</html>

(Vi) loop instruction v-for

(1) Usage

  1. And a list of strings: v-for="(v,i) in str|arr", V is the value, i is an index
  2. Dictionary: v-for="(v,k,i) in dic", V is a value, k is a bond, i is the index
<div id="app">
    <h1>{{ msg }}</h1>
    <!-- n为遍历的元素值 -->
    <ul>
        <li v-for="n in list">{{ n }}</li>
    </ul>
    
    <!-- v-for变量数组[]时,接收两个值时,第一个为元素值,第二个为元素索引 -->
    <ul>
        <li v-for="(n, i) in list" :key="i">value:{{ n }} | index: {{ i }}</li>
    </ul>

    <!-- v-for变量对象{}时,接收三个值时,第一个为元素值,第二个为元素键,第三个为元素索引 -->
    <ul>
        <li v-for="(v, k, i) in dic" :key="k">value:{{ v }} | key:{{ k }} | index: {{ i }}</li>
    </ul>

    <!-- 遍历的嵌套 -->
    <div v-for="(person, index) in persons" :key="index" style="height: 21px;">
        <div v-for="(v, k) in person" :key="k" style="float: left;">{{ k }} : {{ v }}&nbsp;&nbsp;&nbsp;</div>
    </div>
</div>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data: {
            msg: "列表渲染",
            list: [1, 2, 3, 4, 5],
            dic: {
                name: 'zero',
                age: 88888,
                gender: 'god'
            },
            persons: [
                {name: "zero", age: 8},
                {name: "egon", age: 78},
                {name: "liuXX", age: 77},
                {name: "yXX", age: 38}
            ]
        }
    })
</script>

(2) todolist loop instruction based Case

  • Front-end database
    1. localStorage: permanent storage
    2. sessionSrotage: temporary storage (label closed after emptying your page)
    3. First transmission sequence type interaction like array into JSON
    4. Empty database:localStorage.clear();
    5. LocalStorage and can use the dictionary as sessionStorage
<div id="app">
    <input type="text" v-model="comment">
    <button type="button" @click="send_msg">留言</button>
    <ul>
        <li v-for="(msg, i) in msgs" @click="delete_msg(i)">{{ msg }}</li>
    </ul>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            comment: '',
            msgs: localStorage.msgs ? JSON.parse(localStorage.msgs) : [],

        },
        methods: {
            send_msg() {
                // 将comment添加到msgs数组中:unshift push 首尾增 | shift pop 首尾删
                // this.msgs.push(this.comment);

                // 数组操作最全方法:splice(begin_index, count, ...args)
                // this.msgs.splice(0, 2);

                if (!this.comment) {
                    alert('请输入内容');
                    return false;
                }
                this.msgs.push(this.comment);
                this.comment = '';

                localStorage.msgs = JSON.stringify(this.msgs);
            },
            delete_msg(index) {
                this.msgs.splice(index, 1);
                localStorage.msgs = JSON.stringify(this.msgs);
            }
        }
    })
    
     // 前台数据库
    // localStorage: 永久存储
    // sessionStorage:临时存储(所属页面标签被关闭后,清空)

    // 存
    // localStorage.n1 = 10;
    // sessionStorage.n2 = 20;

    // 取
    // console.log(localStorage.n1);
    // console.log(sessionStorage.n2);

    // 数组等类型需要先序列化成JSON
    // localStorage.arr = JSON.stringify([1, 2, 3]);
    // console.log(JSON.parse(localStorage.arr));

    // 清空数据库
    // localStorage.clear();
</script>

(Vii) command v-cloak cloak

  1. When vue introduced on the bottom, because there is no cause vue moment when loading environment flicker
  2. Vue on the head can be introduced in to solve, but in poor network will not be loaded question
  3. Add style by adding v-cloak instruction, and [v-cloak]:{dispaly:none}, flashing rice
<style type="text/css">
    [v-cloak] { display: none; }
</style>

<div id="app" v-cloak>
    {{ msg }}
</div>

<script src="js/vue.min.js"></script>
<script type="text/javascript">
    new Vue({
        el: "#app",
        data: {
            msg: "message"
        }
    })
</script>
<!-- 避免页面闪烁-->

Three, Vue instance members

  1. In Examples Vue outside or other examples, a variable can be defined to accept the example
  2. Examples of methods in Vue, this example refers to itself vue
  3. html - the parameter or variable in the connected hump Vue to convert to the body, such as the background-color to be converted into the backgroundColor, and vice versa

(A) el: Example

  1. Mount point: Vue examples and page tags associated
  2. Mount point using css3 selector syntax, but can only be matched to the first search results, and therefore are usually employed mount point id selector (Uniqueness)
  3. html and body can not be used as a mount point
<div id="app">
    代码
</div>

<script>
    new Vue({
        el:'#app'
    })
    // 实例与页面挂载点一一对应 
    // 一个页面中可以出现多个实例对应多个挂载点
    // 实例只操作挂载点内部内容
</script>

(B) data: Data

  1. Plug-expression: a text-command, support html template syntax{{ 变量名 }}
  2. data to provide data for the plug variables in the expression
  3. Data in the data may be directly or indirectly accessed through examples Vue
<div id="app">
    {{ msg }}
</div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
          msg:"数据"  
        },
    })
    // 在Vue实例外部或者其他实例中,可以定义一个变量接受该实例
    console.log(app.$data.msg)
    console.log(app.msg)
</script>

(C) methods: Method

  1. Based on v-on: the event binding instructions
  2. The method provides methods (logic processing) event
  3. The method of this example refer Vue, corresponding to a function of self python
<div id="app">
    <p v-on:click='pClick'>测试</p>
</div>
<script>
    var app = new Vue({
        el:'#app',
        methods:{
            pClick () {
                // 点击测试
            }
        }
    })
</script>

(D) computed: computing

  1. A variable value applied to a plurality of dependent variable values, such as a simple calculator (two real values ​​and output)
  2. All variable binding methods that appear will be monitored, as long as the changes will start again once the method
  3. The method attribute must be rendered to take effect, rendering the value that is returned to its value
  4. Parameter name computed declared, data can not be repeated statement
<div id="app">
    <input type='text' v-model="a"> <!--v-model为表单指令,相当于value-->
    <input type='text' v-model="b">
    <div>{{ c }}</div>
</div>
<script>
    new Vue({
        el:"#app",
        data:{
            a:'',
            b:'',
        },
        computed:{
            c:function(){
                return this.a + this .b
            }
        }
    })
</script>

(E) watch: monitor

  1. Solve multiple variable value depends on the value of a variable, such as access to the names of the first and last name
  2. Listener properties need to be declared in the data, the method does not require the listener return value
  3. Listening method name is the property name listener will listen for a callback method when the property value changes
  4. Monitor callback method has two parameters: the current value and the first value
<div id="app">
    <input type="text" v-model='fullname'>
    <div>
        {{ a }}
        {{ b }}
    </div>
</div>
<script>
    new Vue({
        el:"#app",
        data:{
            fullname:'',
            surname:'',
            name:"",
        },
        watch:{
            fullname:(n,o){ // n是监听的属性当前值,o是其上一次的值
                this.surname = this.fullname[0];
                this.name = this.fullname[1];
            }
        }
    })
</script>

(Vi) delemiters: delimiter

  1. You can modify the interpolation expression symbols, and avoid the Django framework {{ }}template syntax conflict
  2. delimiters a list of values: ['[{','}]']that is modified[{ }]
<div id="#app">
    ${ msg }
</div>
<script>
    new Vue({
        el:"#app",
        data:{
            msg:"message"
        },
        delimiters:['${','}']
    })
</script>

(Vii) filters: Filters

  1. A plurality of values ​​may be filtered, and the values ​​are in parentheses itself together as a parameter to the filter method
  2. Filtering results can then filtered (filter in series)
<div id="app">
    <!--
    总结:
    1、在filters成员中定义过滤器方法
    2、可以对多个值进行过滤,过滤时还可以额外传入辅助参数
    3、过滤的结果可以再进行下一次过滤(过滤的串联)
    -->
    <p>{{ num | f1 }}</p>
    <p>{{ a, b | f2(30, 40) | f3 }}</p>
</div>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            num: 10,
            a: 10,
            b: 20,
        },
        filters: {
            // 传入所有要过滤的条件,返回值就是过滤的结果
            f1 (num) {
                console.log(num);
                return num * 10;
            },
            f2 (a, b, c, d) {
                console.log(a, b, c, d);
                return a + b + c + d;
            },
            f3 (num) {
                return num * num;
            }
        }
    })
</script>                                   

Four, JS function complements

(A) and custom object constructor

  1. JS the function name is capitalized convention constructor, equivalent to the python classes, can define their own properties and methods, and through it can instantiate a new function object
  2. Custom objects can also be used as an object, you can define your own properties and methods
  3. Constructor method and funtion of this is to refer to instantiate objects out
  4. Custom objects and funtion of this method is to refer to the object itself
// 1. 构造函数 == 类
function F2(name) {
    this.name = name;
    this.eat = function (food) {
        console.log(this.name + '在' + food);
    }
}
let ff1 = new F2("Bob");
console.log(ff1.name);

let ff2 = new F2("Tom");
console.log(ff2.name);

ff1.eat('饺子');
ff2.eat('sao子面');

// 2. 自定义对象
let obj = {
    name: 'Jerry',
    eat: function (food) {
        console.log(this.name + '在' + food)
    },
    // eat(food) {  // 方法的语法
    //     console.log(this.name + '在' + food)
    // }
};
console.log(obj.name);
obj.eat('hotdog');

(B) variable declarations

  1. Statement without words: global variables
  2. const: Constant, not redefine includes a block-level scope
  3. let: Where is the statement of what variables can not be redefined, with block-level scope
  4. var: Global Variables
for (let i = 0; i < 5; i++) {
    console.log(i);
}
console.log(i); // undefined
// 使用var和不声明时,此时i为5

(C) a function of an arrow

  1. Function function may be omitted arrow
  2. Arrow function has no body, only the return value, {} may be omitted
  3. Only one function parameter of the arrow, may be omitted ()
// 匿名函数
let f2 = function () {
    console.log('f2 run');
};
f2();

// 1. 省略function
let f3 = () => {
    console.log('f3 run');
};
f3();

// 2. 如果箭头函数没有函数体,只有返回值
let f4 = (n1, n2) =>  n1 + n2;
let res = f4(10, 25);
console.log(res);

// 3. 如果箭头函数参数列表只有一个,可以省略()
let f5 = num => num * 10;
res = f5(10);
console.log(res);

The difference (D) functions arrows, function and methods

  1. function and methods of this refers to the caller
  2. This refers to the arrow in the function on behalf of the caller on one
  • solve

    Statement by _thisreceiving the original object to refer to this custom variable advance

// 自定义对象
let obj = {
    name: 'Jerry',
    // 1. function中的this指代obj
    eat: function (food) {
        console.log(this)
        console.log(this.name + '在吃' + food)
    },
    // 2. 箭头函数中的this指代obj的上一层:window事件
    eat: food => {
        console.log(this);
        console.log(this.name + '在' + food)
    },
    // 3. 方法中的this指代obj
    eat(food) {  // 方法的语法
        console.log(this);
        console.log(this.name + '在' + food)
    }
};
obj.eat('food');

// Vue实例
new Vue({
        data: {
            res: ''
        },
        methods: {
            fn () {
                // axios插件
                let _this = this;
                this.$axios({
                    url: '',
                    method: 'get',
                    data: {

                    },
                }).then(function (response) {
                    _this.res = response.data;  // 如果是this,指代的是调用者$axios
                })
            },
            
            fn1 () {
                // axios插件
                this.$axios({
                    url: '',
                    method: 'get',
                    data: {

                    },
                }).then(response => {
                    this.res = response.data; // 指代调用者$axios的上一层vue
                })
            }
        }
    })

Fifth, the bubble sort

  1. Compared one by one, depending on the magnitude relation switching position,
  • official
// 按照分数进行排名
    for (let i=0; i<可迭代对象.length-1; i++) {
        for (let j=0; j<可迭代对象.length-1-i; j++) {
            // 处理条件即可
            if ( a>b ) {  // 排序方式
                // 交叉赋值,互换位置
                a,b = b,a
            }
        }
    }
  • Examples
// 对数组排序
let arr = [3, 2, 5, 4, 1];

for (let i = 0; i < arr.length - 1; i++) {  // 外层循环控制趟数
        for (let j = 0; j < arr.length - 1 - i; j++) {  // 内存循环控制比较次数
            if (arr[j] > arr[j + 1]) {
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

// 对字典排序

stus = [
        {
            name: 'Bob',
            grade: 98
        },
        {
            name: 'Tom',
            grade: 87
        },
        {
            name: 'Jerry',
            grade: 92
        },
    ];

// 按照分数进行排名
    for (let i=0; i<stus.length-1; i++) {
        for (let j=0; j<stus.length-1-i; j++) {
            // 处理条件即可
            if (stus[j].grade > stus[j + 1].grade) {
                let temp = stus[j];
                stus[j] = stus[j + 1];
                stus[j + 1] = temp;
            }
        }
    }

Guess you like

Origin www.cnblogs.com/wick2019/p/12079941.html