Vue02_Vue基本指令1/3——内容、事件绑定(v-text/v-html/v-on)

一、 v-text:
  • 用于输出文本
  • 注:{{ }}即插值表达式是v-text的简写形式
    • 区别:v-text会覆盖元素中原本的内容,但是 插值表达式 只会替换自己的这个占位符,不会把 整个元素的内容清空
  • 例:
<body>
    <div id="app">
        <h2 v-text="message"></h2>
    </div>
<script>
    var app = new Vue({
        el: "#app",
        data:{
            message:"Hello!!!"
        }
    })
</script>
</body>
二、 v-html:
  • v-html用于输出html(设置元素的innerHTML属性)
  • 与v-text区别:
    • v-text输出的是纯文本,浏览器不会对其再进行html解析
    • 但v-html会将其当html标签解析后输出
  • 例:
<body>
    <div id="app">
        <h2 v-html="message"></h2>
    </div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"<a href='http://www.baidu.com'>百度</a>"
        }
    })
</script>
</body>
三、 v-on:
  1. 作用:为元素绑定事件
  2. 使用:
  • 直接使用指令v-on(el: / data: / methods: 为同一级)
<body>
    <div id="app">
        <input type="button" value="按钮上的文字" v-on:click="doIt">
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data: {

            },
            methods: {
                doIt:function(){
                    alert("做IT");
                }
            }
        })
    </script>
</body>
  • 使用简化指令@
	<input type="button" value="按钮上的文字" v-on:click="doIt">
    <input type="button" value="按钮上的文字" @click="doIt">
  1. 鼠标事件:
  • click:单击
  • dblclick:双击
  • mousedown:按下任一个鼠标按键时发生
  • mouseup:松开一个鼠标按键时发生
  • mouseover:把鼠标指针移入对象时发生
  • mouseout:把鼠标指针移出对象时发生
  • mousemove:在对象中移动鼠标指针时发生
  1. 例(绑定事件,使得双击添加字符串):
<body>
    <div id="app">
        <h2 @dblclick = "changeMessage"> {{ message }} </h2>
    </div>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"我做的饭"
        },
        methods:{
            changeMessage:function(){
                this.message += "好吃!"
            },
        }
    })
</script>
</body>
  1. 例:(计数器)
  <body>
    <div id="app">
      <!-- 计数器 -->
      <div class="input-num">
        <button @click="sub">
          -
        </button>
        <span>{{ num }}</span>
        <button @click="add">
          +
        </button>
      </div>
    </div>
  </body>
</html>
<!-- 引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  // 创建Vue实例
  var app = new Vue({
    el: "#app",
    data: {
      num: 1,
      min: 0,
      max: 10
    },
    methods: {
      sub() {
        if (this.num > this.min) {
          this.num--;
        } else {
          alert("已到最小值");
        }
      },
      add() {
        if (this.num < this.max) {
          this.num++;
        } else {
          alert("已到最大值");
        }
      }
    }
  });
</script>

效果:
counter.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值