vue3 setup语法糖请注意在script标签里加setup,不用return | 您所在的位置:网站首页 › setup无法打开怎么办 › vue3 setup语法糖请注意在script标签里加setup,不用return |
虽然Composition API用起来已经非常方便了,但是我们还是有很烦的地方,比如 组件引入了还要注册 属性和方法都要在setup函数中返回,有的时候仅一个return就十几行甚至几十行 不想写啊怎么办 好办,Vue3官方提供了script setup语法糖 只需要在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,setup函数也不需要,甚至export default都不用写了,不仅是数据,计算属性和方法,甚至是自定义指令也可以在我们的template中自动获得。 但是这么过瘾的语法糖,还是稍微添加了一点点心智负担,因为没有了setup函数,那么props,emit,attrs怎么获取呢,就要介绍一下新的语法了。 setup script`语法糖提供了三个新的`API`来供我们使用:`defineProps`、`defineEmits`和`useContextdefineProps 用来接收父组件传来的值props。 defineEmits 用来声明触发的事件表。 useContext 用来获取组件上下文context。 父组件 我是父组件! import Child from './components/Child.vue' const handleClick = (ctx) => { console.log(ctx) } 子组件 msg: {{ props.msg }} import { useContext, defineProps, defineEmits } from 'vue' // defineProps 用来接收父组件传来的值props。 // defineEmits 用来声明触发的事件表。 // useContext 用来获取组件上下文context。 const emit = defineEmits(['child-click']) const ctx = useContext() const props = defineProps({ // 可以拿到它的值 msg: String, }) const sonClick = () => { emit('child-click', ctx) } 代码演示子组件先不使用语法糖 我是子组件{{msg}} import { ref } from 'vue' export default { setup() { const msg = ref('hello') return { msg, } }, }现在把子组件换成script setup语法糖再来试一试 我是子组件{{msg}} import { ref } from 'vue' const msg = ref('hello')不必再配合 async 就可以直接使用 await 了,这种情况下,组件的 setup 会自动变成 async setup const post = await fetch('/api').then(() => {})css 变量注入 Jerry import { reactive } from 'vue' const state = reactive({ color: 'red' }) span { // 使用v-bind绑定state中的变量 color: v-bind('state.color'); } nextTick import { nextTick } from 'vue' nextTick(() => { // ... })路由导航守卫 import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router' // 添加一个导航守卫,在当前组件将要离开时触发。 onBeforeRouteLeave((to, from, next) => { next() }) // 添加一个导航守卫,在当前组件更新时触发。 // 在当前路由改变,但是该组件被复用时调用。 onBeforeRouteUpdate((to, from, next) => { next() }) |
CopyRight 2018-2019 实验室设备网 版权所有 |