Vue基础

195 阅读6分钟

Vue插值

数据驱动视图

<body>

<!--视图-->
  <div id="app">
    <!-- {{}} 插值表达式可以插任意的值 -->
    <h2>{{msg}}</h2>
    <h2>{{ 2 }}</h2>
    <h2>{{ 'hello' }}</h2>
    <h2>{{ {id:2} }}</h2>
    <!--加对象时两个中括号与对象的中括号之间一定要有空格-->
    <h2>{{ 1>2 ? '真的':'假的'}}</h2>
    <h2>{{ txt.split('').reverse().join('') }}</h2>
    <h2>{{ getContent() }}</h2>
  </div>
  
<!--数据-->
  <!-- 1.引包 -->
  <script src="vue/vue.js"></script>
  <script>
    //2.初始化
    const vm = new Vue({
      el: '#app', //定位视图
      data: { //数据属性在data里面声明
        msg: 'hello vue',
        txt: 'hello',
        msg2: 'content'
      },
      methods: { //方法函数在methods里面声明
        getContent() {
          return this.msg2; //this指向vm
        }
      }
    });
  </script>
</body>

v-text与v-html

  1. {{ }} 与v-text的作用是一样的 都是插入值 直接渲染 innerText
  2. v-html既能插入值 又能插入标签 innerHTML
<body>
  <div id="id">
    <h1>{{ msg }}</h1>
    <h2 v-text='msg'></h2>
    <div v-html='htmlmsg'></div>
  </div>
  <script src="./vue/vue.js"></script>
  <script>
    new Vue({
      el: '#id',
      data: {
        msg: '插入标签',
        htmlmsg: '<h3>用v-html插入标签</h3>'
      }
    });
  </script>
</body>

条件渲染(v-if 与 v-show)

v-if时 只要布尔值为false 则网页不渲染该div
v-show时 就算布尔值为false 网页也会渲染 只会将该div的style设置为display:none

<body>
  <!-- v-if跟v-show后面跟的都是布尔值 -->
  <div id="id">
    <div v-if='isShow'>随机数大于0.5</div>
    <div v-else>随机数小于0.5</div>

    <div v-show='show'>显示</div>
  </div>
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#id',
      data: {
        isShow: Math.random() > 0.5,
        show: false
      }
    });
  </script>
</body>

两者的使用范围:

v-if适用于不会改变或改变频率较低的情况 因为每次false就会销毁 每次true就会重新渲染

v-true适用于会经常改变的 改变只是改变style的display属性 不需要重新渲染

v-bind(绑定)

v-bind 可以用 : 来表示

<style>
    .active {
      color: red;
    }
</style>

<body>

  <div id="app">
    <a v-bind:href="res.url">{{res.name}}</a>
    <img :src="pic.src" :alt="pic.alt">
    <h3 v-bind:class='{active:isActive}'>v-bind的用法</h3>
    <!-- 当isActive为true时class为active -->
    <h4 :style='{color:isColor,fontSize:fontSize+ "px" }'>hello bind</h4>
  </div>
  
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        pic: {
          src: './imges/u=3861660499,909497754&fm=26&gp=0.jpg',
          alt: '搞笑图片'
        },
        res: {
          url: 'https://www.baidu.com',
          name: '百度'
        },
        isActive: true,
        isColor: 'blue',
        fontSize: 30
      }
    });
  </script>
  
</body>

v-on(事件处理)

v-on 可以用 @来表示

<style>
    .box {
      width: 200px;
      height: 200px;
      background-color: red;
    }

    .active {
      background-color: blue;
    }
</style>
  
<body>

  <div id="app">
    <h3>{{ num }}</h3>
    <button v-on:click='handleClick'>+1</button>
    <div class='box' :class='{active:isActive}'></div>
    <button @click='changClick'>切换</button>
  </div>
  
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        num: 0,
        isActive: false
      },
      methods: {
        handleClick() {
          this.num += 1;
        },
        changClick() {
          this.isActive = !this.isActive
        }
      },
    });
  </script>
  
</body>

事件修饰符

  1. .stop - 调用 event.stopPropagation()。
  2. .prevent - 调用 event.preventDefault()。
  3. .capture - 添加事件侦听器时使用 capture 模式。
  4. .self - 只当事件是从侦听器绑定的元素本身触发时才触发回调。
  5. .{keyCode | keyAlias} - 只当事件是从特定键触发时才触发回调。
  6. .native - 监听组件根元素的原生事件。
  7. .once - 只触发一次回调。
  8. .left - (2.2.0) 只当点击鼠标左键时触发。
  9. .right - (2.2.0) 只当点击鼠标右键时触发。
  10. .middle - (2.2.0) 只当点击鼠标中键时触发。
  11. .passive - (2.3.0) 以 { passive: true } 模式添加侦听器

比较常用

  1. @click.once 表示只有点击的第一次生效
  2. @submit.prevent 提交事件不再重载页面
  3. @keyup.(键别名或者键代码) 表示按下哪个键生效

为什么在HTML中监听事件

  1. 看一眼html模板便能轻松定位在js代码里对应的方法
  2. 无需在js中手动绑定事件,viewModel(vue部分)代码可以使纯粹的逻辑,和dom完全解耦,更易于测试
  3. 当一个ViewModle被销毁时,所有的时间处理器都会被自动的删除,无需担心如何清理它们。

v-for(列表渲染)

v-for='() in ()'
要在后面绑定key :key='().()' 这样在修改列表值的时候只会找到key对应的节点 不会全部列表都重新刷新一遍

  <div id="app">
    <div>
      <ul>
        <li v-for='item in menus' :key = 'item.id'>
          <h3>id:{{item.id}} 菜名:{{item.name}}</h3>
        </li>
      </ul>
      <ol>
        <li v-for='(val,key) in obj'>
          <h3>{{key}}--{{val}}</h3>
        </li>
      </ol>
    </div>
  </div>
  
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        menus: [
          {id: 1,name: '烤韭菜'},
          {id: 2,name: '烤鸡翅'},
          {id: 3,name: '烤土豆'},
          {id: 4,name: '烤鸡心'},
          {id: 5,name: '烤豆腐'},
        ],
        obj:{
          name:'qaq',
          age:20
        }
      },
    })

v-model(双向数据绑定)

  <div id="app">
    <p>{{msg}}</p>
    <input type="text" v-model='msg'>
  </div>
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          msg: 'qaq'
        }
      },
    })
  </script>

事件修饰符

  1. v-model.lazy 不是实时更新 是聚焦不在当前节点时更新
  2. v-model.number自动将用户的输入值转化为数值类型
  3. v-model.trim 会自动清除用户输入的首位空白字符

侦听器watch

基本的数据类型可以使用watch直接监听,复杂的数据类型要深度监视

<body>

  <div id="app">
    <input type="text" v-model='msg'>
    <h3>{{msg}}</h3>
    <h3>{{stus[0].name}}</h3>
    <button @click='stus[0].name="Tom"'>改变</button>
  </div>
  
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        msg: '',
        stus: [{name: 'jack'}]
      },
      watch: {
        // 'key'是属于daya对象的属性名 value:监视后的行为 newV是新值 oldV是旧值
        'msg': function (newV, oldV) {
          console.log(newV, oldV);
        },
        //复杂数据类型需要用到深度监听: Object|Array
        'stus': {
          deep: 'true',
          handler: function (newV, oldV) {
            console.log(newV[0].name);//Tom
          }
        }
      },
    })
  </script>
  
</body>

计算属性computed

计算属性最大的优点是能产生缓存 如果数据没有发生变化 直接从缓存中取

<body>
  <div id="app">
    <h3>{{reverseMsg}}</h3>
    <button @click='change'>改变</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: {
        msg: 'hello computed'
      },
      methods: {
        change() {
          this.msg = '我被改变了'
        }
      },
      computed: {
        //computed默认只有getter方法
        reverseMsg: function () {
          return this.msg.split('').reverse().join('');
        }
      }
    })
  </script>
</body>

computed默认没有setter方法

可以自己创建 拿上面的reverseMsg举例子

computer:{
    reverseMsg:{
        set:function(){
            
        },
        get:function(){
            
        }
    }
}

过滤器filters

<body>

  <div id="app">
    <h3>{{price | myprice('¥')}}</h3>
    <h3>{{msg | myreverse}}</h3>
  </div>
  
  <script src="./vue.js"></script>
  <script>
  
    //创建全局过滤器
    Vue.filter('myreverse', (val) => {
      return val.split('').reverse().join('');
    })
    
    new Vue({
      el: '#app',
      data: {
        price: 10,
        msg: 'hello'
      },
      //局部过滤器
      filters: {
        myprice: function (price, a) {
          return a + price;
        }
      }
    })
  </script>
  
</body>