Vue之自定义指令

2020-02-20  本文已影响0人  弦生_a3a3

Vue 14.自定义指令

<div  id="app">

<input type="text" v-simba>

</div>

类似于v-for或者是v-model的指令

语法:

Vue.directive("simba",{

inserted(el,binding){

//inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)

console.log(el)

//el指当前节点<input type="text">

console.log(binding)

//binding代表里面的一些参数值

}

  })


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>自定义指令</title>

</head>

<style>

</style>

<div id="app">

    <input type="text" v-zxx="time_">

    <div v-upper v-limit="5">

        {{nicname}}

    </div>

    <input type="text" v-len="{changeData}"> {{user}}

</div>

<body>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>

        // 外部定义的一个Vue v-zxx指令

        Vue.directive('zxx', {

            inserted(el, binding) {

                el.value = binding.value

                    //el代表标签

                    //binding代表z-xx里面的参数值

                    // 将这个组件的参数值传给input标签内value值

            }

        })

        Vue.directive('upper', {

                inserted(el, binding) {

                    el.innerHTML = el.innerHTML.toUpperCase()

                        // 因为此时upper里没有值所以需要用到el中的

                }

            })

            //建一个转大写指令

        Vue.directive('limit', {

                inserted(el, binding) {

                    if (el.innerText.length > binding.value) {

                        el.innerHTML = "抱歉!您的用户名已超出字数范围"

                    } else {

                        el.innerHTML = el.innerHTML.toUpperCase()

                    }

                }

            })

            //如果nicnme中长度大于limit组件中的5,则改变el的HTML,否则将el中的HTML转大写

        let vm = new Vue({

            el: "#app",

            data() {

                return {

                    time_: new Date(),

                    nicname: 'acsg',

                    user: '请输入用户名'

                }

            },

            mounted() {

            },

            methods: {

                changeData(val) {

                    return this.user = val;

                }

            },

            directives: {

                len: {

                    inserted: function(el, binding) {

                        el.focus()

                            // 标签聚焦

                        setInterval(e => {

                            if (el.value.length > 7) {

                                binding.value.changeData("抱歉,您的用户名已超出字数范围!")

                            } else {

                                binding.value.changeData(el.value);

                            }

                        }, 10)

                    }

                }

                //在Vue内部建一个len的指令,每10毫秒将标签中的值赋值给data中的user从而实现双向绑定。如果超出字数限制则只呈现超出字数范围,否则将继续绑定

            }

        })

    </script>

</body>

</html>

——————————————————————写的不好,仅供参考

上一篇 下一篇

猜你喜欢

热点阅读