助你从Vue2过渡到Vue3的常见使用场景之一

前言

相信有很多人已经学习了 Vue3 的 API 和 新特性,但是令人头疼的是工作中依然使用的是 Vue2,也不知道自己的水平能否上手 Vue3 项目,今天把实践过程中常见使用场景分享给大家,希望对你们有所帮助。

场景一:父子组件数据传递

父组件数据传递到子组件

Vue3 中父组件同样是通过属性传递数据,但子组件接受数据的方式和 Vue2 不同。在 < script setup > 中,props 需要使用 defineProps() 这个宏函数来进行声明,它的参数和 Vue2 props 选项的值是一样的。

<!-- 父组件 -->
<script setup>
import myChild from './myChild.vue'
</script>

<template>
	<myChild :some-prop="parent message" />
</template>

<!-- 子组件 -->
<script setup>
const props = defineProps({
  childProp: {
    type: String,
    required: true
  }
})
// parent message
console.log(props.childProp) 
</script>

<template>
  <!-- 使用 childProp 或 props.childProp -->
  <div>{{ childProp }}</div>
  <div>{{ props.childProp }}</div>
</template>

注意:defineProps 、defineEmits 、 defineExpose 和 withDefaults 这四个宏函数只能在 <script setup> 中使用。他们不需要导入,会随着 <script setup> 的处理过程中一起被编译。

子组件数据传递到父组件

Vue2 中子组件数据传递到父组件,通常是使用 $emit 触发一个自定义事件来进行传递。但 $emit 无法在 < script setup > 中使用,这时候我们需要使用 defineEmits()

<!-- 子组件 -->
<script setup>
const emit = defineEmits(['childEvent'])
function onClick() {
  emit('childEvent', 'child message')
}
</script>

<template>
  <button @click="onClick">点击</button>
</template>

<!-- 父组件 -->
<script setup>
import myChild from './myChild.vue'

function childEvent(value) {
  // child message
  console.log(value) 
}
</script>

<template>
  <ChildView @child-event="childEvent" />
</template>

父组件使用子组件数据

< script setup > 中,组件的属性和方法默认都是私有的。父组件无法访问到子组件中的任何东西,除非子组件通过 defineExpose 显式的暴露出去:

<!-- 子组件 -->
<script setup>
import { ref } from 'vue'

const msg = ref('vue3!')
function change() {
  msg.value = 'hi vue3!'
}
// 属性或方法必须暴露出去,父组件才能使用
defineExpose({ msg, change })
</script>

<!-- 父组件 -->
<script setup>
import ChildView from './ChildView.vue'
import { ref, onMounted } from 'vue'

const child = ref(null)
onMounted(() => {
  console.log(child.value.msg) // hello vue3!
  child.value.change() // hi vue3!
})
</script>

<template>
  <ChildView ref="child"></ChildView>
</template>

场景二:组件之间双向绑定

大家都知道 Vue2 中组件的双向绑定采用的是 v-model.snyc 修饰符,两种写法多少显得有点重复,于是在 Vue3 中合成了一种。Vue3 统一使用 v-model 进行处理,并且可以和多个数据进行绑定,如 v-model:foo、v-model:bar

  • v-model 等价于 :model-value=“someValue” 和 @update:model-value=“someValue = $event”
  • v-model:foo 等价于 :foo=“someValue” 和 @update:foo=“someValue = $event”

下面就是一个父子组件之间双向绑定的例子:

<!-- 父组件 -->
<script setup>
import myChild from './myChild.vue'
import { ref } from 'vue'

const msg = ref('vue3!')
</script>

<template>
  <ChildView v-model="msg" />
</template>

<!-- 子组件 -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <div @click="emit('update:modelValue', 'hi vue3!')">{{ modelValue }}</div>
</template>

子组件可以结合 input 使用:

<!-- 子组件 -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>

如果你觉得上面的模板比较繁琐,也可以结合 computed 一起使用:

<!-- 子组件 -->
<script setup>
import { computed } from 'vue'

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const newValue = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
</script>

<template>
  <input v-model="newValue" />
</template>

场景三:路由跳转,获取路由参数

在 Vue2 中我们通常是使用 this.\$router 或 this.$route 来进行路由的跳转和参数获取,但在 < script-setup > 中,是这些方法无法使用的。我们可以使用 vue-router 提供的 useRouter 方法,来进行路由跳转:

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()
function onClick() {
  router.push({
    path: '/hone',
    query: {
      msg: 'earth'
    }
  })
}
</script>

当我们要获取路由参数时,可以使用 vue-router 提供的 useRoute 方法:

<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
console.log(route.query.msg)
</script>

场景四:获取上下文对象

Vue3 的 setup 中无法使用 this 这个上下文对象。可能刚接触 Vue3 的兄弟会有点懵,我想使用 this 上的属性和方法应该怎么办呢。虽然不推荐这样使用,但依然可以通过 getCurrentInstance 方法获取上下文对象:

<script setup>
import { getCurrentInstance } from 'vue'

// 以下两种方式都可以获取到上下文对象
const { ctx } = getCurrentInstance()
const { proxy }  = getCurrentInstance()
</script>

值得注意的是 ctx 只能在开发环境使用,生成环境为 undefined 。 推荐使用 proxy ,在开发环境和生产环境都可以使用。
其他 APITypeScript 结合使用的方法和上面大同小异,具体可以参考这篇文章: 何为 Vue3 组件标注 TS 类型,看这篇文章就够了!

小结

以上就是我在 Vue3 项目中遇到最多的场景,如果你掌握了 Vue3 常用的 API 和今天这些场景,相信参与 Vue3 项目的开发是没有问题了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shansec~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值