vue基础

1.vue基本使用

vm:el / data
v:v-model / {{  }}

1. 引入Vue.js
2. 创建Vue对象
    el : 指定根element(选择器)
    data : 初始化数据(页面可以访问)
3. 双向数据绑定 : v-model
4. 显示数据 : {{xxx}}
5. 理解vue的mvvm实现
    > view:模板页面
    > 	    自定义标签属性:指令
    > 	    大括号表达式:获取模型数据
    > viewModel:vue实体 
    > model:模型 (data)
    > element: 指定用vue来管理页面中的哪个标签区域
<!--模板-->
<div id="test">
  <input type="text" v-model="msg"><br><!--指令-->
  <input type="text" v-model="msg"><!--指令-->
  <p>hello {{msg}}</p><!--大括号表达式-->
</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  const vm = new Vue({ // 配置对象 options
    // 配置选项(option)
    el: '#test',  // element: 指定用vue来管理页面中的哪个标签区域
    data: {
      msg: 'atguigu'
    }
  })
</script>

2.vue模板语法

vm:el  / data /  methods
v:{{  }} / :href / @click

1. 模板的理解:
  动态的html页面
  包含了一些JS语法代码
    大括号表达式
    指令(以v-开头的自定义标签属性)

2. 双大括号表达式
  语法: {{exp}}{{{exp}}}
  功能: 向页面输出数据
  可以调用对象的方法

3. 指令一: 强制数据绑定
  功能: 指定变化的属性值
  完整写法:
    v-bind:xxx='yyy'  //yyy会作为表达式解析执行
  简洁写法:
    :xxx='yyy'

4. 指令二: 绑定事件监听
  功能: 绑定指定事件名的回调函数
  完整写法:
    v-on:click='xxx'
  简洁写法:
    @click='xxx'

  回调函数:1.你定义的;2.你没有调用;3.但最终它执行了。
  回调函数:什么时候调用?用来做什么?
<div id="app">
  <h2>1. 双大括号表达式</h2>
  <p>{{content}}</p>
  <p>{{content.toUpperCase()}}</p>

  <h2>2. 指令一: 强制数据绑定</h2>
  <a href="url">访问指定站点</a><br>
  <a v-bind:href="url">访问指定站点2</a><br>
  <a :href="url">访问指定站点2</a><br>

  <h2>3. 指令二: 绑定事件监听</h2>
  <button v-on:click="test">点我</button>
  <button @click="test">点我</button>

</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: '#app',
    data: {
      content: 'NBA I Love This Game',
      url: 'http://www.atguigu.com'
    },
    methods: {
      test () {
        alert('好啊!!!')
      }
    }
  })
</script>

3.计算属性与监视

vm:el / data / computed / watch / vm.$watch
v:v-model / {{  }}

1. 计算属性
  在computed属性对象中定义计算属性的方法
  在页面中使用{{方法名}}来显示计算的结果

2. 监视属性:
  通过通过vm对象的$watch()或watch配置来监视指定的属性
  当属性变化时, 回调函数自动调用, 在函数内部进行计算

3. 计算属性高级:
  通过getter/setter实现对属性数据的显示和监视
  计算属性存在缓存, 多次读取只执行一次getter计算
  getter:属性的get方法
  setter:属性的set方法
<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>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  const vm = new Vue({
    el: '#demo',
    data: {
      firstName: 'A',
      lastName: 'B',
       fullName2: 'A-B'
    },

    // 计算属性配置: 值为对象
    computed: {
      fullName1 () { // 属性的get()
        console.log('fullName1()', this)
        return this.firstName + '-' + this.lastName
      },

      fullName3: {
        // 当获取当前属性值时自动调用, 将返回值(根据相关的其它属性数据)作为属性值
        get () {
          console.log('fullName3 get()')
          return this.firstName + '-' + this.lastName
        },
        // 当属性值发生了改变时自动调用, 监视当前属性值变化, 同步更新相关的其它属性值
        set (value) {// fullName3的最新value值  A-B23
          console.log('fullName3 set()', value)
          // 更新firstName和lastName
          const names = value.split('-')
          this.firstName = names[0]
          this.lastName = names[1]
        }
      }
    },

    watch: {
      // 配置监视firstName
      firstName: function (value) { // 相当于属性的set
        console.log('watch firstName', value)
        // 更新fullName2
        this.fullName2 = value + '-' + this.lastName
      }
    }
  })

  // 监视lastName
  vm.$watch('lastName', function (value) {
    console.log('$watch lastName', value)
    // 更新fullName2
    this.fullName2 = this.firstName + '-' + value
  })
</scrip>

4.强制绑定class和style

vm:el  / data /  methods
v::class / :style / @click

1. 理解
  在应用界面中, 某个()元素的样式是变化的
  class/style绑定就是专门用来实现动态样式效果的技术
2. class绑定: :class='xxx'
  xxx是字符串
  xxx是对象
  xxx是数组
3. style绑定
  :style="{ color: activeColor, fontSize: fontSize + 'px' }"
  其中activeColor/fontSize是data属性
<style>
    .classA {
      color: red;
    }
    .classB {
      background: blue;
    }
    .classC {
      font-size: 20px;
    }
</style>
<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>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  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'
      }
    }
  })
</scrip>

5.条件渲染

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>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: "#demo",
    data: {
      ok: true,
    }
  })
</scrip>

6.列表渲染

1. 列表显示
  数组: v-for / index
  对象: v-for / key
2. 列表的更新显示
  删除item
  替换item
<div id="demo">
  <h2>测试: v-for 遍历数组</h2>
  <ul>
    <li v-for="(p, index) in persons" :key="index">
      {{index}}--{{p.name}}--{{p.age}}
      --<button @click="deleteP(index)">删除</button>
      --<button @click="updateP(index, {name:'Cat', age: 16})">更新</button>
    </li>
  </ul>
  <button @click="addP({name: 'xfzhang', age: 18})">添加</button>

  <h2>测试: v-for 遍历对象</h2>

  <ul>
    <li v-for="(item, key) in persons[1]" :key="key">{{key}}={{item}}</li>
  </ul>

</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: '#demo',
    data: {
      persons: [
        {name: 'Tom', age:18},
        {name: 'Jack', age:17},
        {name: 'Bob', age:19},
        {name: 'Mary', age:16}
      ]
    },

    methods: {
      deleteP (index) {
        // splice(index,len,[item])
        // index:数组开始下标
        // len: 替换/删除的长度
        // item:替换的值,删除操作的话 item为空
        this.persons.splice(index, 1) // 调用了不是原生数组的splice(), 而是一个变异(重写)方法
              // 1. 调用原生的数组的对应方法
              // 2. 更新界面
      },

      updateP (index, newP) {
        console.log('updateP', index, newP)
        // this.persons[index] = newP  // vue根本就不知道
        this.persons.splice(index, 1, newP)
        // this.persons = []
      },

      addP (newP) {
        this.persons.push(newP)
      }
    }
  })
</scrip>

7.列表过滤和排序

1. 列表过滤
2. 列表排序
<div id="demo">
  <input type="text" v-model="searchName">
  <ul>
    <li v-for="(p,index) in filterPersons">
      {{index}}--{{p.name}}--{{p.age}}
    </li>
  </ul>
  <button @click="setOrderType(1)">年龄升序</button>
  <button @click="setOrderType(2)">年龄降序</button>
  <button @click="setOrderType(0)">原本顺序</button>
</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: "#demo",
    data: {
      searchName: "",
      orderType: 0,
      persons: [
        {name:"Tom",age:18},
        {name:"Jack",age:19},
        {name:"Bob",age:16},
        {name:"Mack",age:17},
      ],
    },
    computed: {
      filterPersons(){
        //取出相关的数据
        const {searchName,persons,orderType}=this
        //最终需要显示的数组
        let fPersons;
        //对persons进行过滤
        fPersons = persons.filter(p => p.name.indexOf(searchName) !== -1)

        //排序
        if(orderType!==0){
          fPersons.sort(function(p1,p2){  //返回正数,p2在前;返回负数,p1在前
            if(orderType === 2){
              return p2.age-p1.age
            }else{
              return p1.age-p2.age
            }
          })
        }

        return fPersons
      }
    },
    methods: {
      setOrderType(orderType){
        this.orderType = orderType
      }
    }
  })
</scrip>

8.事件处理

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" @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>
  <input type="text" @keyup.13="test7">
  <input type="text" @keyup.enter="test7">

</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: '#example',
    data: {

    },
    methods: {
      test1(event){
        alert(event.target.innerHTML)
      },
      test2(msg){
        alert(msg)
      },
      test3(msg,event){
        alert(msg+"--"+event.target.innerHTML)
      },

      test4(event){
        // event.preventDefault()   阻止事件默认行为
        alert("百度一下");
      },
      test5(){
        alert("out")
      },
      test6(event){
        // event.stopPropagation()  停止事件冒泡行为
        alert("inner")
      },

      test7(event){
        alert(event.target.value+' '+event.keyCode)
      }
    }
  })
</scrip>

9.表单输入绑定

使用v-model(双向数据绑定)自动收集数据
  text/textarea
  checkbox
  radio
  select
<div id="demo">
  <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>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  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请求')
      }
    }
  })
</scrip>

10.vue的生命周期

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">显示与隐藏</p>
</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: "#test",
    data: {
      isShow: true,
    },

    //1. 初始化
    beforeCreate(){
      console.log("beforeCreate()")
    },
    created(){
      console.log("created()")
    },

    beforeMount(){
      console.log("beforeMount()")
    },
    mounted(){  //初始化显示之后立即调用(1次)
      console.log("mounted()")
      this.intervalId = setInterval(() => {
        console.log("---------")
        this.isShow = !this.isShow
      },1000)
    },

    //2.更新
    beforeUpdate(){
      console.log("beforeUpdate()")
    },
    updated(){
      console.log("updated()")
    },

    //3.销毁
    beforeDestroy(){  //死亡之前调用(1次)
      console.log("beforeDestroy()")
      //清楚定时器
      clearInterval(this.intervalId)
    },
    destroyed(){
      console.log("destroyed()")
    },

    methods: {
      destroyVue(){
        //干掉vm
        this.$destroy()
      }
    }
  })
</scrip>

11.过渡与动画

1. vue动画的理解
  操作css的transition或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、xxx-leave-to: 指定隐藏时的样式
<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>
<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>

<scrip type="text/javascript" src="../js/vue.js"></script>
<scrip>
  new Vue({
    el: '#demo',
    data: {
      show: true
    }
  })

  new Vue({
    el: '#demo2',
    data: {
      show: true
    }
  })
</scrip>

12.过滤器

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>{{date}}</p>
  <p>完整版:{{date | dateString}}</p>
  <p>年月日:{{date | dateString('YYYY-MM-DD')}}</p>
  <p>时分秒:{{date | dateString('HH:mm:ss')}}</p>
</div>

<scrip type="text/javascript" src="../js/vue.js"></script>
<!--使用cdn引入moment.js库-->
<scrip src="https://cdn.bootcss.com/moment.js/2.24.0/moment.js"></script>
<scrip>
  //在创建 Vue 实例之前全局定义过滤器
  //format="YYYY-MM-DD HH:mm:ss" 形参默认值,format有值时为当前值,没值时为右边默认值
  Vue.filter("dateString",function (value,format="YYYY-MM-DD HH:mm:ss") {
    return moment(value).format(format)
  })

  //创建 Vue 实例
  new Vue({
    el: "#test",
    data: {
      date: new Date()
    },
    mounted: function () {  //初始化显示之后立即调用(1次)
      //启动定时器
      setInterval(() =>{
        this.date = new Date()
      },1000)
    }
  })
</scrip>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值