Vue method function filing

  vue.js

ArticleIt has been published on personal blogs and is constantly updated. Welcome to collect and subscribe, or make criticism.

Some methods and functions may not be used very often, but they cannot be remembered when meeting the needs of a specific scene. Therefore, it is necessary to record these methods and functions encountered at ordinary times and query them when necessary.

  1. String inversion
  2. Todos
  3. Check form
  4. Dynamic options, rendering with v-for
  5. Instruction instance properties
  6. Object literal
  7. MVVM data binding
  8. Use v-if or v-show to determine the condition.
  9. Directive
  10. Dynamic component
  11. Use script or template tags
  12. Use props
  13. Use script or template tags

String inversion

reverseMessage: function () {
    this.msg = this.msg.split('').reverse().join('')
}

Todos

<div id="app">
    <input v-model="newTodo" v-on:keyup.enter="addTodo">
    <ul>
        <li v-for="(todo,index) in todos">
            <span>{{todo.text}}</span>
            <button v-on:click="removeTodo(index)">X</button>
        </li>
    </ul>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<!--<script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.js"></script>-->
<script>
    new Vue({
        data: {
            newTodo: '',
            todos: [
                {text: 'Add some todos'}
            ]
        },
        methods: {
            addTodo: function () {
                var text = this.newTodo.trim();
                if (text) {
                    this.todos.push({text: text});
                    this.newTodo = ''
                }
            },
            removeTodo: function (index) {
                this.todos.splice(index, 1)
            }
        }
    }).$mount('#app')
</script>

Check form

<div id="app">
    <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
    <label for="jack">Jack</label>
    <input type="checkbox" id="john" value="john" v-model="checkedNames">
    <label for="john">John</label>
    <input type="checkbox" id="mike" value="mike" v-model="checkedNames">
    <label for="mike">Mike</label>
    <br>
    <span>Checked names: {{checkedNames}}</span>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            checkedNames:[]
        }
    })
</script>

Dynamic options, rendering with v-for

<div id="app">
    <select v-model="selected">
        <option v-for="option in options" v-bind:value="option.value">
            {{option.text}}
        </option>
    </select>
    <br>
    <span>Selected: {{selected}}</span>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            selected:'A',
            options:[
                {text:'One',value:'A'},
                {text:'Two',value:'B'},
                {text:'Three',value:'C'}
            ]
        }
    })
</script>

Instruction instance properties

<div id="app">
    <div id="demo" v-demo:hello.a.b="msg"></div>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.directive('demo', {
        bind() {
            document.write('demo bound! This is a test dialog.')
        },
        update(value) {
            this.el.innerHTML =
                `name - ` + this.name + `<br>` +
                `expression - ` + this.expression + `<br>` +
                `argument - ` + this.arg + `<br>` +
                `modifiers - ` + JSON.stringify(this.modifiers) + `<br>` +
                `value - ` + value
        }
    });

    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'Hello Vue.js!'
        }
    })
</script>

Object literal

<div id="app">
    <div v-demo="styleObj"></div>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.directive('demo', () => {
        console.log(styleObj.color);
        console.log(styleObj.text)
    });
    var styleObj = {
        color: 'red',
        text: 'Hello!'
    };
    var vm = new Vue({
        el: '#app',
        data: {
            styleObj: styleObj
        }
    })
</script>

MVVM data binding

<!-- 指令 -->
<span v-text="msg"></span>
<!-- 插值 -->
<span>{{msg}}</span>
<!-- 双向绑定 -->
<input v-model="msg"> 

Use v-if or v-show to determine the condition.

<div id="app">
    <section v-if="loginStatus">
        输入您的姓名:<input type="text" v-model="name">
        <button @click="say">欢迎点击</button>
        <button @click="switchLoginStatus">退出登录</button>
    </section>

    <section v-if="!loginStatus">
        登录用户:<input type="text">
        登录密码:<input type="password">
        <button @click="switchLoginStatus">登录</button>
    </section>
</div>

<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    var vm = new Vue({
        data: {
            name: '_Appian',
            loginStatus: true
        },
        methods: {
            say: function () {
                alert('欢迎' + this.name)
            },
            switchLoginStatus: function () {
                this.loginStatus = !this.loginStatus;
            }
        }
    }).$mount('#app')
</script>

Directive

Verify what Todo List has entered (form verification). The basic logic lies inbindPhase when binding events, and then according to theupdateWhen the incoming minlength value to judge.

Directive’s basic structure is as follows:

Vue.directive("minlength", {
    bind: function () {
    },
    update: function (value) {
    },
    unbind: function () {
    }
});
Vue.directive("minlength", {
    bind: function () {
        var self = this,
            el = this.el;
        el.addEventListener("keydown", function (e) {
            if (e.keyCode === 13) {
                if (el.value.length < self.minlength) {
                    e.preventDefault();
                }
            }
        });
        var submit = el.parentNode.querySelector("button,[type='submit']");
        submit.disabled = true;
        el.addEventListener("keyup", function (e) {
            submit.disabled = (el.value.length < self.minlength);
        })
    },
    update: function (value) {
        this.minlength = parseInt(value);
    },
    unbind: function () {

    }
});

Dynamic component

<div id="app">
    <button id="home">Home</button>
    <button id="posts">Posts</button>
    <button id="archive">Archive</button>
    <br>
    <component :is="currentView"></component>
</div>
var vm = new Vue({
    data: {
        currentView: "home"
    },
    components: {
        home: {
            template: `<div>Home</div>`
        },
        posts: {
            template: `<div>Posts</div>`
        },
        archive: {
            template: `<div>Archive</div>`
        }
    }
}).$mount('#app');

document.getElementById('home').onclick = function () {
    vm.currentView = "home";
};
document.getElementById('posts').onclick = function () {
    vm.currentView = "posts";
};
document.getElementById('archive').onclick = function () {
    vm.currentView = "archive";
};

Use script or template tags

Use script tags

<div id="app">
    <my-component></my-component>
</div>
<script type="text/x-template" id="myComponent">
    <div>This is a test component.</div>
</script>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.component('my-component', {
        template: `#myComponent`
    });

    new Vue({
        el: "#app"
    });
</script>

Use template label

<div id="app">
    <my-component></my-component>
</div>
<template id="myComponent">
    <div>This is a test component.</div>
</template>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.component('my-component', {
        template: `#myComponent`
    });

    new Vue({
        el: "#app"
    });
</script>

Use props

The scope of the component instance is isolated. This means that the data of the parent component cannot and should not be directly referenced within the template of the child component. Can be usedpropsPass the data to the subcomponents.

Props basic example

// 将父组件数据通过已定义好的props属性传递给子组件
<div id="app">
    <my-component :my-name="name" :my-age="age"></my-component>
</div>
<template id="myComponent">
    <table>
        <thead>
        <tr>
            <th colspan="2">
                子组件数据
            </th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>my name</td>
            <td>{{myName}}</td>
        </tr>
        <tr>
            <td>my age</td>
            <td>{{myAge}}</td>
        </tr>
        </tbody>
    </table>
</template>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            name: 'keepfool',
            age: 28
        },
        components: {
            'my-component': {
                template: `#myComponent`,
                props: ['myName', 'myAge']
            }
        }
    });
</script>

If we want to use the data of the parent component, we must first define it in the child component.propsProperty, that isprops: [‘myName', ‘myAge']This line of code.

Note:Defined in subcomponentspropWhen using thecamelCaseNomenclature. Because HTML features are not case sensitive,camelCaseThepropFor features, you need to convert tokebab-case(separated by dashes). For example, inpropAs defined inmyNameWhich needs to be converted to when used as a propertymy-name.

When using a child component in a parent component, data is passed to the child component by the following syntax:

<child-component v-bind:子组件prop="父组件数据属性"></child-component>

Binding type for prop

Unidirectional binding

  1. The data of the child component was modified without affecting the data of the parent component.
  2. The data of the parent component was modified and the child components were affected.

propThe default is one-way binding: when the attribute of the parent component changes, it will be conducted to the child component, but not vice versa. This is to prevent the child component from inadvertently modifying the state of the parent component.

Bidirectional binding

Can be used.syncExplicitly specify bidirectional binding, which causes data modifications of child components to be passed back to the parent component.