vue常用指令代码实例总结


Posted in Python onMarch 16, 2020

vue常用内置指令

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>12_指令_内置指令</title>
 <style>
  [v-cloak] { display: none }
 </style>
</head>
<body>
<!--
常用内置指令
 v:text : 更新元素的 textContent
 v-html : 更新元素的 innerHTML
 v-if : 如果为true, 当前标签才会输出到页面
 v-else: 如果为false, 当前标签才会输出到页面
 v-show : 通过控制display样式来控制显示/隐藏
 v-for : 遍历数组/对象
 v-on : 绑定事件监听, 一般简写为@
 v-bind : 强制绑定解析表达式, 可以省略v-bind
 v-model : 双向数据绑定
 ref : 为某个元素注册一个唯一标识, vue对象通过$refs属性访问这个元素对象
 v-cloak : 使用它防止闪现表达式, 与css配合: [v-cloak] { display: none }
-->
<div id="example">
 <p v-cloak>{{content}}</p>
 <p v-text="content"></p>  <!--p.textContent = content-->
 <p v-html="content"></p> <!--p.innerHTML = content-->
 <p ref="msg">abcd</p>
 <button @click="hint">提示</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#example',
  data: {
   content: '<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" >百度一下</a>'
  },
  methods: {
   hint () {
    alert(this.$refs.msg.innerHTML)
   }
  }
 })
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
  <div id="app">
    <!-- 数据绑定 -->
    <a v-bind:href="url" rel="external nofollow" >百度一下</a>
    <!-- 双向数据绑定 -->
    <input type="text" v-model="name">
    <p>{{name}}</p>
    
    <!-- 绑定回车键 -->
    <input type="text" @keyup.enter="showEnt">
    <!-- 点击事件 -->
    <button @click="show('888')">按钮</button>
    <!-- 获取数组值 -->
    <p>{{arr[1]}}</p>
    <!-- 获取对象属性 -->
    <p>{{users[1].name}}</p>
  </div>
  <script>
    var app = new Vue({
      el: "#app",
      data: {
        name:'',
        url: 'http://www.baidu.com',
        arr: ["a", "b", "c", "d"],
        users: [
          { name: "aowei", age: 12 },
          { name: "baozi", age: 13 },
          { name: "bbbbb", age: 14 },
        ]
      },
      methods: {
        // 绑定回车键
        showEnt: function () {
          alert("666");
        },
        // 传参
        show: function (num) {
          alert(num);
        }
      },
    }
    )
  </script>
</body>
</html>

计算属性和监视

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>03_计算属性和监视</title>
</head>
<body>
<!--
1. 计算属性
 在computed属性对象中定义计算属性的方法
 在页面中使用{{方法名}}来显示计算的结果
2. 监视属性:
 通过通过vm对象的$watch()或watch配置来监视指定的属性
 当属性变化时, 回调函数自动调用, 在函数内部进行计算
3. 计算属性高级:
 通过getter/setter实现对属性数据的显示和监视
 计算属性存在缓存, 多次读取只执行一次getter计算
-->
<div id="demo">
 姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
 名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
 <!--fullName1是根据fistName和lastName计算产生-->
 姓名1(单向): <input type="text" placeholder="Full Name1" v-model="fullName1"><br>
 姓名2(单向): <input type="text" placeholder="Full Name2" v-model="fullName2"><br>
 姓名3(双向): <input type="text" placeholder="Full Name3" v-model="fullName3"><br>
 <p>{{fullName1}}</p>
 <p>{{fullName1}}</p>
</div>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
 const vm = new Vue({
  el: '#demo',
  data: {
   firstName: 'A',
   lastName: 'B',
   fullName2: 'A-B'
  },
  // 计算属性配置: 值为对象
  computed: {
   fullName1:function() { // 属性的get()
    return this.firstName + '-' + this.lastName;
   },
   fullName3: {
    // 当获取当前属性值时自动调用, 将返回值(根据相关的其它属性数据)作为属性值
    get () {
     return this.firstName + '-' + this.lastName
    },
    // 当属性值发生了改变时自动调用, 监视当前属性值变化, 同步更新相关的其它属性值
    set (value) {// fullName3的最新value值 A-B23
     // 更新firstName和lastName
     const names = value.split('-')
     this.firstName = names[0]
     this.lastName = names[1]
    }
   }
  },
  watch: {
   // 配置监视firstName
   firstName: function (value) { // 相当于属性的set
    // 更新fullName2
    this.fullName2 = value + '-' + this.lastName
   }
  }
 })
 // 监视lastName
 vm.$watch('lastName', function (value) {
  // 更新fullName2
  this.fullName2 = this.firstName + '-' + value
 })
</script>
</body>
</html>

列表渲染

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <ul>
      <li v-for='item in arr'>
        {{item}}
      </li>
    </ul>
    <ul>
      <li v-for="(item,index) in arr">
        {{index}} --- {{item}}
      </li>
    </ul>
    <h3 v-for="user in users" v-bind:title="user.name">
      {{user.name}} --- {{user.age}}
    </h3>
    <button @click="add">add按钮</button>
    <button @click="del">del按钮</button>
  </div>
  <script>
    var app = new Vue({
      el: "#app",
      data: {
        arr: ["a", "b", "c", "d"],
        users: [
          { name: "aowei", age: 12 },
          { name: "baozi", age: 13 },
          { name: "bbbbb", age: 14 },
        ]
      },
      methods: {
        add: function () {
          console.log("add");
          this.users.push({ name: "hello", age: "3" });
        },
        del: function () {
          console.log("del");
          this.users.shift();
        }
      },
    }
    )
  </script>
</body>
</html>

class & style 绑定

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>04_class与style绑定</title>
 <style>
  .classA {
   color: red;
  }
  .classB {
   background: blue;
  }
  .classC {
   font-size: 20px;
  }
 </style>
</head>
<body>
<!--
1. 理解
 在应用界面中, 某个(些)元素的样式是变化的
 class/style绑定就是专门用来实现动态样式效果的技术
2. class绑定: :class='xxx'
 xxx是字符串
 xxx是对象
 xxx是数组
3. style绑定
 :style="{ color: activeColor, fontSize: fontSize + 'px' }"
 其中activeColor/fontSize是data属性
-->
<div id="demo">
 <h2>1. class绑定: :class='xxx'</h2>
 <p :class="myClass">xxx是字符串</p>
 <p :class="{classA: hasClassA, classB: hasClassB}">xxx是对象</p>
 <p :class="['classA', 'classB']">xxx是数组</p>
 <h2>2. style绑定</h2>
 <p :style="{color:activeColor, fontSize}">:style="{ color: activeColor, fontSize: fontSize + 'px' }"</p>
 <button @click="update">更新</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#demo',
  data: {
   myClass: 'classA',
   hasClassA: true,
   hasClassB: false,
   activeColor: 'red',
   fontSize: '20px'
  },
  methods: {
   update () {
    this.myClass = 'classB'
    this.hasClassA = !this.hasClassA
    this.hasClassB = !this.hasClassB
    this.activeColor = 'yellow'
    this.fontSize = '30px'
   }
  }
 })
</script>
</body>
</html>

条件渲染

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>08_条件渲染</title>
</head>
<body>
<!--
1. 条件渲染指令
 v-if
 v-else
 v-show
2. 比较v-if与v-show
 如果需要频繁切换 v-show 较好
-->
<div id="demo">
 <p v-if="ok">表白成功</p>
 <p v-else>表白失败</p>
 <hr>
 <p v-show="ok">求婚成功</p>
 <p v-show="!ok">求婚失败</p>
 <button @click="ok=!ok">切换</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#demo',
  data: {
   ok: true,
  }
 })
</script>
</body>
</html>

事件处理

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>07_事件处理</title>
</head>
<body>
<!--
1. 绑定监听:
 v-on:xxx="fun"
 @xxx="fun"
 @xxx="fun(参数)"
 默认事件形参: event
 隐含属性对象: $event
2. 事件修饰符:
 .prevent : 阻止事件的默认行为 event.preventDefault()
 .stop : 停止事件冒泡 event.stopPropagation()
3. 按键修饰符
 .keycode : 操作的是某个keycode值的健
 .enter : 操作的是enter键
-->
<div id="example">
 <h2>1. 绑定监听</h2>
 <button @click="test1">test1</button>
 <button @click="test2('abc')">test2</button>
 <button @click="test3('abcd', $event)">test3</button>
 <h2>2. 事件修饰符</h2>
 <!-- 阻止事件默认行为 -->
 <a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" @click.prevent="test4">百度一下</a>
 <div style="width: 200px;height: 200px;background: red" @click="test5">
  <div style="width: 100px;height: 100px;background: blue" @click.stop="test6"></div>
  <!-- 阻止事件冒泡 -->
 </div>
 <h2>3. 按键修饰符</h2>
 <!-- enter键/13 -->
 <input type="text" @keyup.13="test7">
 <input type="text" @keyup.enter="test7">
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#example',
  data: {
  },
  methods: {
   test1(event) {
    alert(event.target.innerHTML)
   },
   test2 (msg) {
    alert(msg)
   },
   test3 (msg, event) {
    alert(msg+'---'+event.target.textContent)
   },
   test4 () {
    alert('点击了链接')
   },
   test5 () {
    alert('out')
   },
   test6 () {
    alert('inner')
   },
   test7 (event) {
    console.log(event.keyCode)
    alert(event.target.value)
   }
  }
 })
</script>
</body>
</html>

表单数据绑定

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>08_表单输入绑定</title>
</head>
<body>
<!--
1. 使用v-model(双向数据绑定)自动收集数据
 text/textarea
 checkbox
 radio
 select
-->
<div id="demo">
 <!-- 阻止表单自动提交,手动ajax提交 -->
 <form action="/xxx" @submit.prevent="handleSubmit"> 
  <span>用户名: </span>
  <input type="text" v-model="username"><br>
  <span>密码: </span>
  <input type="password" v-model="pwd"><br>
  <span>性别: </span>
  <input type="radio" id="female" value="女" v-model="sex">
  <label for="female">女</label>
  <input type="radio" id="male" value="男" v-model="sex">
  <label for="male">男</label><br>
  <span>爱好: </span>
  <input type="checkbox" id="basket" value="basket" v-model="likes">
  <label for="basket">篮球</label>
  <input type="checkbox" id="foot" value="foot" v-model="likes">
  <label for="foot">足球</label>
  <input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
  <label for="pingpang">乒乓</label><br>
  <span>城市: </span>
  <select v-model="cityId">
   <option value="">未选择</option>
   <option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option>
  </select><br>
  <span>介绍: </span>
  <textarea rows="10" v-model="info"></textarea><br><br>
  <input type="submit" value="注册">
 </form>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#demo',
  data: {
   username: '',
   pwd: '',
   sex: '男',
   likes: ['foot'],
   allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}],
   cityId: '2',
   info: ''
  },
  methods: {
   handleSubmit () {
    console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
    alert('提交注册的ajax请求')
   }
  }
 })
</script>
</body>
</html>

生命周期

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>09_Vue实例_生命周期</title>
</head>
<body>
<!--
1. vue对象的生命周期
 1). 初始化显示
  * beforeCreate()
  * created()
  * beforeMount()
  * mounted()
 2). 更新状态
  * beforeUpdate()
  * updated()
 3). 销毁vue实例: vm.$destory()
  * beforeDestory()
  * destoryed()
2. 常用的生命周期方法
 created()/mounted(): 发送ajax请求, 启动定时器等异步任务
 beforeDestory(): 做收尾工作, 如: 清除定时器
-->
<div id="test">
 <button @click="destroyVue">destory vue</button>
 <p v-if="isShow">尚硅谷IT教育</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#test',
  data: {
   isShow: true
  },
  beforeCreate() {
   console.log('beforeCreate()')
  },
  created() {
   console.log('created()')
  },
  beforeMount() {
   console.log('beforeMount()')
  },
  mounted () {
   console.log('mounted()')
   // 执行异步任务
   this.intervalId = setInterval(() => {
    console.log('-----')
    this.isShow = !this.isShow
   }, 1000)
  },
  beforeUpdate() {
   console.log('beforeUpdate()')
  },
  updated () {
   console.log('updated()')
  },
  beforeDestroy() {
   console.log('beforeDestroy()')
   // 执行收尾的工作
   clearInterval(this.intervalId)
  },
  destroyed() {
   console.log('destroyed()')
  },
  methods: {
   destroyVue () {
    this.$destroy()
   }
  }
 })
</script>
</body>
</html>

过渡,动画

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>10_过渡&动画1</title>
 <style>
  /*指定过渡样式*/
  .xxx-enter-active, .xxx-leave-active {
   transition: opacity 1s
  }
  /*指定隐藏时的样式*/
  .xxx-enter, .xxx-leave-to {
   opacity: 0;
  }
  .move-enter-active {
   transition: all 1s
  }
  .move-leave-active {
   transition: all 3s
  }
  .move-enter, .move-leave-to {
   opacity: 0;
   transform: translateX(20px)
  }
 </style>
</head>
<body>
<!--
1. vue动画的理解
 操作css的trasition或animation
 vue会给目标元素添加/移除特定的class
2. 基本过渡动画的编码
 1). 在目标元素外包裹<transition name="xxx">
 2). 定义class样式
  1>. 指定过渡样式: transition
  2>. 指定隐藏时的样式: opacity/其它
3. 过渡的类名
 xxx-enter-active: 指定显示的transition
 xxx-leave-active: 指定隐藏的transition
 xxx-enter: 指定隐藏时的样式
-->
<div id="demo">
 <button @click="show = !show">Toggle</button>
 <transition name="xxx">
  <p v-show="show">hello</p>
 </transition>
</div>
<hr>
<div id="demo2">
 <button @click="show = !show">Toggle2</button>
 <transition name="move">
  <p v-show="show">hello</p>
 </transition>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 new Vue({
  el: '#demo',
  data: {
   show: true
  }
 })
 new Vue({
  el: '#demo2',
  data: {
   show: true
  }
 })
</script>
</body>
</html>

过滤器

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>11_过滤器</title>
</head>
<body>
<!--
1. 理解过滤器
 功能: 对要显示的数据进行特定格式化后再显示
 注意: 并没有改变原本的数据, 可是产生新的对应的数据
2. 编码
 1). 定义过滤器
  Vue.filter(filterName, function(value[,arg1,arg2,...]){
   // 进行一定的数据处理
   return newValue
  })
 2). 使用过滤器
  <div>{{myData | filterName}}</div>
  <div>{{myData | filterName(arg)}}</div>
-->
<!--需求: 对当前时间进行指定格式显示-->
<div id="test">
 <h2>显示格式化的日期时间</h2>
 <p>{{time}}</p>
 <p>最完整的: {{time | dateString}}</p>
 <p>年月日: {{time | dateString('YYYY-MM-DD')}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script>
<script>
 // 定义过滤器
 Vue.filter('dateString', function (value, format='YYYY-MM-DD HH:mm:ss') {
  return moment(value).format(format);
 })
 new Vue({
  el: '#test',
  data: {
   time: new Date()
  },
  mounted () {
   setInterval(() => {
    this.time = new Date()
   }, 1000)
  }
 })
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>12_指令_自定义指令</title>
</head>
<body>
<!--
1. 注册全局指令
 Vue.directive('my-directive', function(el, binding){
  el.innerHTML = binding.value.toupperCase()
 })
2. 注册局部指令
 directives : {
  'my-directive' : {
    bind (el, binding) {
     el.innerHTML = binding.value.toupperCase()
    }
  }
 }
3. 使用指令
 v-my-directive='xxx'
-->
<!--
需求: 自定义2个指令
 1. 功能类型于v-text, 但转换为全大写
 2. 功能类型于v-text, 但转换为全小写
-->
<div id="test">
 <p v-upper-text="msg"></p>
 <p v-lower-text="msg"></p>
</div>
<div id="test2">
 <p v-upper-text="msg"></p>
 <p v-lower-text="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
 // 注册一个全局指令
 // el: 指令所在的标签对象
 // binding: 包含指令相关数据的容器对象
 Vue.directive('upper-text', function (el, binding) {
  console.log(el, binding)
  el.textContent = binding.value.toUpperCase()
 })
 new Vue({
  el: '#test',
  data: {
   msg: "I Like You"
  },
  // 注册局部指令
  directives: {
   'lower-text'(el, binding) {
    console.log(el, binding)
    el.textContent = binding.value.toLowerCase()
   }
  }
 })
 new Vue({
  el: '#test2',
  data: {
   msg: "I Like You Too"
  }
 })
</script>
</body>
</html>

本文主要介绍了vue常用指令代码实例,更多关于vue常用指令请查看下面的相关链接

Python 相关文章推荐
Python查询Mysql时返回字典结构的代码
Jun 18 Python
Python可变参数函数用法实例
Jul 07 Python
python 的列表遍历删除实现代码
Apr 12 Python
Python 基础之字符串string详解及实例
Apr 01 Python
简单实现python数独游戏
Mar 30 Python
基于python的多进程共享变量正确打开方式
Apr 28 Python
python实现周期方波信号频谱图
Jul 21 Python
3个用于数据科学的顶级Python库
Sep 29 Python
对python读写文件去重、RE、set的使用详解
Dec 11 Python
django认证系统实现自定义权限管理的方法
Aug 28 Python
Django项目基础配置和基本使用过程解析
Nov 25 Python
详解Python中的GIL(全局解释器锁)详解及解决GIL的几种方案
Jan 29 Python
django-利用session机制实现唯一登录的例子
Mar 16 #Python
python安装dlib库报错问题及解决方法
Mar 16 #Python
使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实例
Mar 16 #Python
关于win10在tensorflow的安装及在pycharm中运行步骤详解
Mar 16 #Python
Python3.6 中的pyinstaller安装和使用教程
Mar 16 #Python
python pandas利用fillna方法实现部分自动填充功能
Mar 16 #Python
Python Flask上下文管理机制实例解析
Mar 16 #Python
You might like
如何对PHP程序中的常见漏洞进行攻击
2006/10/09 PHP
php socket方式提交的post详解
2008/07/19 PHP
PHP下escape解码函数的实现方法
2010/08/08 PHP
IIS6.0 开启Gzip方法及PHP Gzip函数分享
2014/06/08 PHP
PHP中类的继承和用法实例分析
2016/05/24 PHP
PHP自定义错误用法示例
2016/09/28 PHP
PHP长连接实现与使用方法详解
2018/02/11 PHP
PHP从零开始打造自己的MVC框架之路由类实现方法分析
2019/06/03 PHP
PHP设计模式之 策略模式Strategy详解【对象行为型】
2020/05/01 PHP
遍历jquery对象的代码分享
2011/11/02 Javascript
JQuery 图片的展开和伸缩实例讲解
2013/04/18 Javascript
常用js字符串判断方法整理
2013/10/18 Javascript
当某个文本框成为焦点时即清除文本框内容
2014/04/28 Javascript
cocos2dx骨骼动画Armature源码剖析(一)
2015/09/08 Javascript
又一款js时钟!transform实现时钟效果
2016/08/15 Javascript
js事件源window.event.srcElement兼容性写法(详解)
2016/11/25 Javascript
Javascript之面向对象--封装
2016/12/02 Javascript
JavaScript中数组Array.sort()排序方法详解
2017/03/01 Javascript
关于vue.js过渡css类名的理解(推荐)
2017/04/10 Javascript
javascript 面向对象实战思想分享
2017/09/07 Javascript
[01:43]深扒TI7聊天轮盘语音出处4
2017/05/11 DOTA
初步介绍Python中的pydoc模块和distutils模块
2015/04/13 Python
使用Python的Zato发送AMQP消息的教程
2015/04/16 Python
把项目从Python2.x移植到Python3.x的经验总结
2015/04/20 Python
更改Ubuntu默认python版本的两种方法python-&gt; Anaconda
2016/12/18 Python
Python常见工厂函数用法示例
2018/03/21 Python
浅谈pycharm下找不到sqlalchemy的问题
2018/12/03 Python
使用Python快速制作可视化报表的方法
2019/02/03 Python
解决python中使用PYQT时中文乱码问题
2019/06/17 Python
python实现PCA降维的示例详解
2020/02/24 Python
python爬虫请求头设置代码
2020/07/28 Python
大四学年自我鉴定
2013/11/13 职场文书
高三毕业寄语
2014/04/10 职场文书
做一个有道德的人活动方案
2014/08/25 职场文书
mysql如何配置白名单访问
2021/06/30 MySQL
SQL bool盲注和时间盲注详解
2022/07/23 SQL Server