vue3新语法糖 |
您所在的位置:网站首页 › 狞笑的读音 › vue3新语法糖 |
前言
vue3上线已经很久了,许多小伙伴应该都已经使用过vue3了。那么在使用vue3composition API的时候有没有觉得整个过程会比较繁琐呢。比如当你定义了一个方法,然后发现模板需要使用该方法,然后就必须将方法返回。当一个组件中存在大量方法和属性的时候,这个过程就会非常的难受。 什么是setup scriptsetup script就是vue3新出的一个语法糖,使用方法就是在书写script标签的时候在其后面加上一个setup修饰。 复制代码看上去是不是很简单呢? vue3 + ts + setup script + volar最佳实践(在ts中使用setup script看这篇) 看到这里很多小伙伴就不理解了,我在script后面加上一个setup有什么用呢?接着看! 1> 自动注册子组件什么意思? 现在有两个组件,父组件Father.vue,子组件Child.vue。 vue3语法 我是父组件! import { defineComponent, ref } from 'vue'; import Child from './Child.vue' export default defineComponent({ components: { Child }, setup() { return { } } }); 复制代码vue3语法在引入Child组件后,需要在components中注册对应的组件才可使用。 setup script写法 我是父组件!-setup script import Child from './Child.vue' 复制代码这么一对比是不是就非常明了了呢?直接省略了子组件注册的过程。 2> 属性和方法无需返回重点来了,之前说composition API写起来有点繁琐的原因在于需要手动返回模板需要使用的属性和方法。而在setup script中可以省略这一步。看看下面的例子。 vue3语法 {{ name }} is {{ age }} import { defineComponent, ref } from 'vue'; export default defineComponent({ setup() { const name = ref('CoCoyY1') const age = ref(18) const ageInc = () => { age.value++ } return { name, age, ageInc } } }) 复制代码setup script写法 {{ name }} is {{ age }} import { ref } from 'vue'; const name = ref('CoCoyY1') const age = ref(18) const ageInc = () => { age.value++ } 复制代码哇哦,是不是非常方便呢? 3> 支持props、emit和context看到这里可能有小伙伴会问,没了setup()那怎么获取到props和context呢?来! vue3语法 //Father.vue 我是父组件! import { defineComponent, ref } from 'vue'; import Child from './Child.vue'; export default defineComponent({ components: { Child }, setup(props, context) { const childCtx = (ctx) => { console.log(ctx); } return { childCtx } } }) //Child.vue 我是子组件! -- msg: {{ props.msg }} import { defineComponent, ref } from 'vue' export default defineComponent({ emits: [ 'child-click' ], props: { msg: String }, setup(props, context) { const handleClick = () => { context.emit('child-click', context) } return { props, handleClick } }, }) 复制代码点击一下子组件看看打印了什么。 很明显是成功的打印出了context,这是vue3的语法。 setup script写法 //Father.vue 我是父组件! import Child from './Child.vue'; const childCtx = (ctx) => { console.log(ctx); } //Child.vue 我是子组件! -- msg: {{ props.msg }} import { useContext, defineProps, defineEmit } from 'vue' const emit = defineEmit(['child-click']) const ctx = useContext() const props = defineProps({ msg: String }) const handleClick = () => { emit('child-click', ctx) } 复制代码点击子组件看看使用语法糖时context能不能正确打印。 这里可以看到context被打印了出来,其中的attrs、emit、props、slots、expose属性和方法依然可以使用。 那就对了,setup script语法糖提供了三个新的API来供我们使用:defineProps、defineEmit和useContext。 其中defineProps用来接收父组件传来的值props。defineEmit用来声明触发的事件表。useContext用来获取组件上下文context。 对比一下两种写法,是不是setup script更加简洁方便呢? 但是!!! 注意我引入三个API的顺序,在此时如果把useContext放在最后引入,那么.... 报错!!! 这应该是一个bug吧,想不出其他解释了。 以上就是vue3新出的语法糖setup script的基本使用方法了,是不是很香呢?笔者认为这个语法糖应该会成为一个正式的内容,因为它真的可以说是非常方便简洁了。 写在最后 (^.^)如果觉得我写的还不错的话,可以赏我个点赞哦^.^ 如果有写错的地方、写的不好的地方也请大家指出,供我纠正。 我是CoCoyY1,一个记录自己学习的前端热爱者。 我的其他文章Vue3中的expose函数 ———— 控制组件被ref时暴露的对象内容 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |