Vue13 -- 指令系统

常用指令

1) v:text : 更新元素的 textContent
2) v-html : 更新元素的 innerHTML
3) v-if : 如果为 true, 当前标签才会输出到页面
4)v-else: 如果为 false, 当前标签才会输出到页面
5) v-show : 通过控制 display 样式来控制显示/隐藏
6) v-for : 遍历数组/对象
7) v-on : 绑定事件监听, 一般简写为@
8) v-bind : 强制绑定解析表达式, 可以省略 v-bind
9) v-model : 双向数据绑定
10) ref : 指定唯一标识, vue 对象通过$els 属性访问这个元素对象
11) v-cloak : 防止闪现, 与 css 配合: [v-cloak] { display: none }

内置指令实例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            [v-cloak]{
                display: none;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <p ref='content' >内容内容</p>
            <button @click="btn"> 提示 </button>
            <p v-cloak>{{msg}}</p>
            
        </div>
        
        <script src="https://vuejs.org/js/vue.js"></script>
        <script type="text/javascript">
            var app = new Vue({
                el:'#app',
                data:{
                    msg:'一个小不点'
                },
                methods:{
                    btn(){
                        alert(this.$refs.content.textContent)
                    }
                }
            })
        </script>
    </body>
</html>

自定义指令

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app1">
            <p v-upper-text='msg1'></p>
            <p v-lower-text='msg1'></p>
        </div>
        
        <div id="app2">
            <p v-upper-text='msg2'></p>
        </div>
        
        <script src="https://vuejs.org/js/vue.js"></script>
        <script type="text/javascript">
            //定义全局指令
            // el:  指令所对应的标签对象
            //binding:包含指令相关的数据对象
            Vue.directive('upper-text',function  (el,binding) {
                el.textContent = binding.value.toUpperCase()
            })
            
            var app1 = new Vue({
                el:'#app1',
                data:{
                    msg1:'This is a apple'
                },
                directives:{
                    'lower-text'(el,binding) {
                        return   el.textContent = binding.value.toLowerCase()
                    }
                }
            })
            
            var app2 = new Vue({
                el:'#app2',
                data:{
                    msg2:'Just Do It'
                }
            })
        </script>
    </body>
</html>
原文地址:https://www.cnblogs.com/lee-xingxing/p/11216798.html