Vue3与Vue2中方法的变化

1: v-if与v-for的优先级(更新)

原则上,在vue中应该避免在同一元素上使用 v-if 与 v-for 的。

  • 2.x:v-for 的优先级高于 v-if
  • 3.x:v-if 的优先级高于 v-for

2: 关于 computed: 3.X 把 computed 变成了一个计算属性 API,所以可以有多个 computed,可以沿用 Vue.js 2.x 的使用方法

// vue2.x
computed: {
  loading() {
    return !this.list.length
  }
},

// vue3.x
const loading = computed(() => !this.list.length)
const titleList = computed(() => {
return props.data.map((item) => item.title)
})

3: 关于 watch:对于监听对象是分隔字符串时,需要在选项参数中指定 deep: true

// vue2.x
watch: {
    'data.distance': function (newVal, oldVal) {
      if (newVal === constants.DISTANCE_ON) {
        ...
      }
    },
},

// vue3.x
watch(
   () => this.data.distance,
   (newVal, oldVal) => {
        if (newVal === constants.DISTANCE_ON) {
            ...
        }
   },
   { deep: true },
 )

4: 在 Vue3 中组件没有filters选项,迁移过程中,可以用computed/methods替代

// vue2.x
filters: {
    // just a method
    dateFormat,
},

// vue3.x
const dateFormat = computed(() => {
    // just a method
    dateFormat,
})

5: vue3.X 中去掉了.sync,用v-model代替 并且同一个组件中不仅限于只有一个v-model

<!-- vue2.x -->
<!-- 父组件 -->
<template>   
    <p>{{title}}</p>
    <syncDemo :title.sync="title"> </syncDemo>
</template>
 
<!-- 子组件 -->
<template>
  <div>
    <!--约定该事件名,必须为update:后加上需要更新的props即title-->
    <button @click="$emit('update:title','aaa123')">点我</button>
  </div>
</template>
<script>
export default {
  props:{
    title:{
      type:String,
    }
  }
}
</script>


<!-- vue3.x -->
<!-- 父组件 -->
<template>
    <!-- 自定义 v-model -->
    <p>{{title}}</p>
    <CustomVModel v-model="title"/>
</template>
 
<!-- 子组件 -->
<template>
  <div>
    <button @click="$emit('update:title','aaa123')">点我</button>
  </div>
</template>
<script>
export default {
  props:{
    title:{
      type:String,
    }
  }
}
</script>

6: v-bind的合并策略(更新)

在同一个元素上,对某个属性同时使用单属性和使用v-bind同时定义,就像下面这样:

<!-- 情况1 -->
<div id="abc" v-bind="{ id: 'def' }"></div>
<!-- 情况2 -->
<div v-bind="{ id: 'def' }" id="abc"></div>

上面两种情况会被编译成下面的结果:

<!-- vue2.x -->
<!-- 情况1/情况2   单个属性的值优先级更好,会覆盖掉使用 v-bind 所定义的属性-->
<div id="abc"></div>

<!-- vue3.x -->
<!-- 情况1 -->
<div id="def"></div>
<!-- 情况2 -->
<div id="abc"></div>

7: keyCodes(更新)

在2.X中,为一些元素绑定键盘事件的方式是只用 keyCodes 来标识不同的按键,keyCodes 作为修改 v-on 的一种方式:

<!-- keyCode version -->
<input v-on:keyup.13="submit" />

<!-- alias version -->
<input v-on:keyup.enter="submit" />

<!-- 还可以通过全局配置来定义一些常用按键的别名 -->
<!-- keyCode version -->
<input v-on:keyup.112="showHelpText" />

<!-- custom alias version -->
<input v-on:keyup.f1="showHelpText" />

Vue.config.keyCodes = {
  f1: 112
}

在3.x中,由于 keyboardEvent.keyCode 已弃用,因此不在支持此功能,取而代之的是将 kebab-case 名称作为修饰符:

<input v-on:keyup.delete="confirmDelete" />
<input v-on:keyup.c="confirmC" />
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容