Vue tutorial series - basic syntax v1.0

Keywords: Javascript Vue Attribute JQuery

Catalog

  1. helloWorld

  2. Bidirectional binding

  3. css operation

  4. Style operation

  5. Binding events

  6. Binding event - modifier

  7. life cycle

  8. v-if show and hide (1)

  9. v-show show show and hide (2)

  10. v-for rendering list (Key)

  11. Array update

  12. couputed association properties (calculator properties)

  13. watch to listen for changes (listen to array and object need to add deep parameter, immediate)

  14. refs get element

  15. Asynchronous update

  16. helloWorld and two-way binding (this is a complete example, the latter only has body part)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hello world</title>
    <script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
</head>
<body>
    <h3>hello world</h3><hr>
    <div id="app">
        <p>{{ message }}</p>
        <input v-model="username" />
        <p>{{username}}</p>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: 'Hello Vue.js!',
                username: 'Front-end of fertile soil'
            }
        })
    </script>
</body>
</html>
  1. css and style rendering
<style type="text/css">
    div {margin: 5px;}
    .active {border: 1px solid green;}
    .error {color: red;}
</style>
// Method 1: when isActive is true, add class' active 'to the element
<div id="app">
    <div v-bind:class="{ active: isActive }">binding class style</div>
<div :class="{ active: isActive }">class Style (abbreviation)</div>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            isActive: true,
            isError: true
        }
    })
</script>

// Method 2: add a class as a class
<div id="app">
      <div :class="classObj">object</div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            classObj: {
                active: true,
                error: true
            }
        }
    })

// Method 3: add class by array
<div id="app">
    <div :class="[activeClass, errorClass]">Array method</div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            activeClass: 'active',
            errorClass: 'error'
        }
    })
</script>

// Method 4: add class by expression
<div id="app">
    <div :class="isActive ? 'active' : ''">Using expressions</div>
    <div :class="[isActive ? 'active' : '', isError?'error':'']">Use two expressions at the same time</div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            isActive: true,
            isError: true
        }
    })
</script>

  1. Event handler and event modifier: https://cn.vuejs.org/v2/guide/events.html
<div id="example-3" @click="clickFather()">
    <button v-on:click="say('hi')">Say hi</button><br />
    <button v-on:click="say('what')">Say what</button><br />
    <button v-on:click.stop="doThis">stop(Prevent events from bubbling)</button>
</div>
<script type="text/javascript">
    new Vue({
        el: '#example-3',
        methods: {
            say(message) {
                alert(message)
            },
            doThis() {
                alert('stop');
            },
            clickFather() {
                console.log('You clicked on the parent element');
            }
        }
    })
</script>
  1. life cycle
<div id="app">
    <p>{{msg}}</p>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'life cycle'
        },
        // After the instance is created, the element in el has not been replaced. You can send a request
        created() {
            console.log('create');
        },
        // After mounting, the element in el is replaced, and the page element can be operated
        mounted() {
            console.log('mounted');
        }
    })
</script>
  1. Render list
// (1) in order to optimize rendering efficiency, the rendering list should add: key="index"
<div id="app">
    <ul style="list-style: none;">
        <li v-for="(item, index) in items" :key="index">
            <span>{{ index }}</span>
            <span>Name-{{item.name}}</span>
            <span> Place of Origin-{{ item.addr }}</span>
        </li>
    </ul>
</div>

<script type="text/javascript">
    var example2 = new Vue({
        el: '#app',
        data: {
            items: [{
                    name: 'Apple',
                    addr: 'Shandong'
                },
                {
                    name: 'Banana',
                    addr: 'Hainan'
                }
            ]
        }
    })
</script>

// (2) update a data in the list
<div id="app">
    <ul style="padding: 0;list-style: none;">
        <li v-for="(item, index) in items" :key="index">
            <span>{{ index }}</span>
            <span>Name-{{item.name}}</span>
            <span> Place of Origin-{{ item.addr }}</span>
        </li>
    </ul>
    <button @click="update()">Update all properties of member 1</button><br />
    <button @click="update1()">Update a property of member 1</button><br />
    <button @click="update2()">Update member 2</button><br />
</div>

<script type="text/javascript">
    new Vue({
        el: '#app',
        data: {
            items: [{
                    name: 'Apple',
                    addr: 'Shandong'
                },
                {
                    name: 'Banana',
                    addr: 'Hainan'
                }
            ]
        },
        methods: {
            update() {
                // Update all properties of member 1
                this.$set(this.items, 0, {
                    name: 'Pomegranate',
                    addr: 'Shanxi'
                });
            },
            update1() {
                // If you only want to change the value of one attribute of one member object of the array, and other attributes do not change, you can write as follows
                this.$set(this.items, 0, { ...this.items[0],
                    name: 'tomato'
                });
            },
            update2() {
                // The second way to update array objects
                this.items.splice(0, 1, {
                    name: 'Snow pear',
                    addr: 'Guangxi'
                });

            }
        }
    })
</script>

  1. Asynchronous update component Vue.nextTick, for example, chestnut. Here is an example of adding a rotation chart
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link href="https://cdn.bootcss.com/Swiper/4.0.0-beta.2/css/swiper.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/Swiper/4.0.0-beta.2/js/swiper.min.js"></script>
    <script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
    <!-- Demo styles -->
    <style> html, body { position: relative; height: 100%; }  body { background: #fff; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; color: #000; margin: 0; padding: 0; }  .swiper-container { width: 300px; height: 300px; position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -150px; }  .swiper-slide { background-position: center; background-size: cover; } </style>
</head>
<body>
    <div id="app">
        <div class="swiper-container">
            <div class="swiper-wrapper">
                <div v-for="item in list" class="swiper-slide" :key="item.id"
                    :style=`backgroundImage:url(${item.url})`>
                </div>
            </div>
            <div class="swiper-pagination"></div>
        </div>
    </div>

    <script type="text/javascript">
        new Vue({
            el: '#app',
            data: {
                msg: 'aaa',
                list: []
            },
            mounted() {
                this.add();
            },

            methods: {
                add() {
                    var url = 'http://www.easy-mock.com/mock/59b89b82e0dc663341a7cced/vue/imgList';
                    $.get(url, (res) => {
                        this.list = res.list;
                        // Wait until the picture is loaded, or it will not take effect
                        this.$nextTick(()=> {
                            this.addCarousel();
                        })
                    })
                },
                // Add a carousel
                addCarousel() {
                    var swiper = new Swiper('.swiper-container', {
                        effect: 'cube',
                        loop: true
                    });
                }
            }
        })
    </script>
</body>
</html>
  1. Calculated attribute
<div id="app">
    <div id="example">
        <p>message: "{{ message }}"</p>
        <p>Flip string: "{{ reversedMessage }}"</p>
    </div>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: '#example',
        data: {
            message: 'Hello'
        },
        computed: {
            // Generate a new attribute based on message
            reversedMessage: function () {
                return this.message.split('').reverse().join('')
            }
        }
    })
</script>
  1. watch (listen to array or object need to add deep parameter, immediate)
<div id="app">
    <p>News:{{msg}}</p>
    <p>Object property value a: {{obj.a}}</p>
    <button @click="updateMsg">Modify the value of the message</button><br />
    <button @click="updateObj">modify attribute a Value</button>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'hello',
            obj: {
                a: 2,
                b: 3
            },
            tip:''
        },
        methods: {
            updateMsg() {
                this.msg = 'haha';
            },
            updateObj() {
                this.obj.a = '222';
            }
        }
    })
    // The value of watch msg
    vm.$watch('msg', function(newValue, oldValue) {
        console.log('New value:'+newValue,'Old values:'+oldValue);
    })
    // Some parameters need to be added to the properties of the watch object
    vm.$watch('obj', function (obj) {
        console.log(obj.a);
    }, {
        // No callback will be triggered without this parameter
         deep: true,
        // If this parameter is available, the callback will be triggered immediately. obj does not need to be changed
        immediate: true
    })
</script>

//Summary: the same function can be realized by computed and watch. When computed can be used, it is usually computed, which is more concise. Reference address: http://www.cnblogs.com/annie211/p/7324631.html
9.1 custom components

<div id="app">
<!--Use components-->
    <Hello></Hello>
    <Second></Second>
</div>

<script type="text/javascript">
    // Declare the Hello component
    var Hello = {
        template: '<p>{{userName}}</p>',
        data() {
            return {
                userName: 'I am Lao Hu.'
            }
        }
    }
    // Declare the Second component
    var Second = {
        template: '<p>{{msg}}</p>',
        data() {
            return {
                msg: 'This is the second component'
            }
        }
    }

    new Vue({
        el: '#app',
        data: {
            msg: '2222' 
        },
        // Registration component
        components: {
            Hello,
            Second
        }
    })
</script>

9.2 pass parameters props from parent component to child component

<div id="app">
    <!-- parentMsg1 Hyphen required -->
    <Hello parent-msg1="hello" :parent-msg2="msg"></Hello>
    <!--Dynamic binding parameters-->
    <input v-model="msg" />
</div>

<script type="text/javascript">
    // To define a subcomponent First, note that template can only have one root label
    var Hello = {
        template: `<div><p>Static parameter:{{ parentMsg1 }}</p>
        <p>dynamic parameter: {{parentMsg2}}</p></div>`,
        props: ['parentMsg1','parentMsg2'],
        data() {
            return {}
        }
    }

    new Vue({
        el: '#app',
        data: {
            msg: 'Ha ha ha'
        },
        components: {
            Hello
        }
    })
</script>

9.3 $emit of subcomponent (subcomponent passes value to parent)

<div id="app">
    <p>{{ total }}</p>
    <!--Pass a function to a subcomponent-->
    <Counter @add="count"></Counter>
</div>

<script type="text/javascript">
    // Sub components
    var Counter = {
        template: '<button @click="myClick()">increase</button>',
        data: function () {
            return {
                num: 0
            }
        },
        methods: {
            myClick: function () {
                // Trigger the add function of the parent component
                this.$emit('add',222)
            }
        },
    }

    // Parent component
    new Vue({
        el: '#app',
        data: {
            total: 0
        },
        components: {
            Counter
        },
        methods: {
            count: function (param) {
                // param can receive the parameter returned from the subcomponent
                console.log(param);
                this.total += 1
            }
        }
    })
</script>

10 custom component v-model (for non input tags)
Please refer to the link: https://segmentfault.com/a/1190000008662112

11 single file component is generally used in current projects

// Template
<template>
    <div class="wrap">
        <h3>Single file component</h3>
        <p>{{msg}}</p>
    </div>
</template>

// js code
<script>
export default {
    data() {
        return {
            msg: 'hello world'
        }
    }
}
</script>

// style
<style lang="less" scoped>
.wrap {
    border: 1px solid;
    height: 100px;
    h3 {
        color: red;
    }
    p {
        background: gray;
    }
}
</style>
github address of this tutorial: https://github.com/wotu-courses/vue_basics.git
To participate in the offline technical exchange of wotu front end community (Shenzhen), please add wechat

Posted by Kiubbo on Mon, 09 Dec 2019 19:03:14 -0800