牡丹江建设信息网站,龙岗中心医院,flash网站建设技术精粹,成都网站营销script setup是 Vue 3 中引入的一种新的组件内脚本语法糖#xff0c;它带来了更简洁、高效的组件逻辑编写方式。
以下是 script setup 的主要语法元素和特性#xff1a;
1.导入和使用
直接在 script setup 中导入依赖#xff0c;不需要在 compon…script setup是 Vue 3 中引入的一种新的组件内脚本语法糖它带来了更简洁、高效的组件逻辑编写方式。
以下是 script setup 的主要语法元素和特性
1.导入和使用
直接在 script setup 中导入依赖不需要在 components、directives 等选项中声明。导入的组件和指令可以直接在模板中使用。
2.响应式数据:
使用 ref 和 reactive 来创建响应式的数据。ref 用于基本类型reactive 用于对象。示例
import { ref, reactive } from vueconst count ref(0)
const state reactive({ message: Hello World })
3.计算属性:
使用 computed 来定义计算属性。示例
import { computed } from vueconst reversedMessage computed(() state.message.split().reverse().join())
4.侦听器:
使用 watch 和 watchEffect 来监听数据的变化。示例
import { watch, watchEffect } from vuewatch(count, (newVal, oldVal) {console.log(count changed from ${oldVal} to ${newVal})
})watchEffect(() {console.log(current count value is: ${count.value})
})
5.生命周期钩子:
可以直接在 script setup 中使用生命周期钩子如 onMounted, onUnmounted,onBeforeUpdate、onUpdated、onBeforeUnmount 和 onUnmounted 等等。示例
import { onMounted, onUnmounted } from vueonMounted(() {console.log(Component mounted)
})onUnmounted(() {console.log(Component unmounted)
})
6.Props 解构:
使用defineProps编译宏来定义组件接收的属性它接收一个对象或者基于类型的声明。在组件使用时就能接收外部传入的对应属性值了并且在模板中可以像使用普通变量一样使用props中的属性。使用 defineProps 接收父组件传递的 props。示例
templatediv{{ title }}/div
/templatescript setup
// 基于对象的方式定义props
const props defineProps({title: String
})
// 基于类型的方式如果使用TypeScript
// const props defineProps{ title: string }()
/script
7.事件处理:
使用defineEmits编译宏来声明组件向外触发的自定义事件。示例
templatebutton clickemitCustomEvent触发事件/button
/templatescript setup
const emits defineEmits([custom-event])
const emitCustomEvent () {emits(custom-event, 传递的数据)
}
/script
8. 默认导出: 不再需要 export default因为所有顶层绑定会自动暴露给模板。
9.解构 Props 和 Emits:
直接解构 props 和 emit 而无需担心失去响应性。示例
const { title, isActive } defineProps([title, isActive])
const emit defineEmits([update:title]) 10.访问父组件和根实例属性有限制
在script setup中访问父组件或根实例的属性不像传统的this.$parent或this.$root那样方便不过可以通过getCurrentInstance函数但官方不建议过度依赖此方式用于普通场景主要用于一些高级的、框架层面的扩展等情况来获取组件实例相关信息。例如
script setup
import { getCurrentInstance } from vue
const instance getCurrentInstance()
// 可以通过instance来访问一些实例相关信息不过要谨慎使用
/script