setup语法糖
<script setup>
//这里的代码会被编译成组件setup()函数中的内容,这里的script跟普通的script只有组件首次引入的时候执行一次不同,<script setup>中的代码会在每次组件实例被创建的时候执行
</script>
基本使用
<script setup>
//这里跟setup函数一样的写法,只是不需要return,组件不需要挂在compones上,可以直接在模板上使用
import { reactive, ref } from '@vue/reactivity'
import { computed, watch, watchEffect } from '@vue/runtime-core'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import HelloWorld from './components/HelloWorld.vue'
import headerModule from './components/js/headerModule'
const data = ({
})
</script>
<template>
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
defineProps,defineEmits,defineExpose它们都是<script setup>
中才能使用的编译器宏,不需要引入直接可以使用,会随着 <script setup>
处理过程一同被编译掉
父传子
<template>
<!--父组件-->
<HelloWorld msg="Hello" />
</template>
<script setup>
//子组件通过defineProps代替props
const porps = definePorps({
fol:{
type:String,
default:'默认值',
require:true//设置之后,props必须要接收到这个数据,默认为false
}
})
</script>
<template>
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
子传父
<script setup>
//使用defineEmits代替$emit
const emit = defineEmits(['change'])//这里最好写出来
const change = val=>{
emit("change",val)
}
</script>
<template>
<!--<div @click="emit('biu',123)">子组件</div> 这样写前面可以加$用之前的写法也行-->
<div @click="change(111)">子组件</div>
</template>
暴露组件
<script>
//使用<script setup>的组件默认是关闭的,它的公开实例不会暴露在里面声明的绑定
//使用defineExpose暴露数据
const a = ref(1)
const b = 2
defineExpose({
a,
b
})
</script>
父组件通过模板绑定ref,获取到这个对象
<script setup>
//得先声明个变量,来保存它,或者放在onMounted里
const hello = ref(null)
const get = ()=>{
console.log(hello)
}
</script>
<template>
<Header @click="get" ref="hello">子组件</Header>
</template>
自定义指令
<script setup>
//全局自定义指令一样用,本地指令可以直接在模板上使用,但是必须以 vNameOfDirective 的形式来命名本地自定义指令
const vMyDirective = {
beforeMount: (el) => {
console.log(el)
}
}
</script>
<template>
<div v-my-directive></div>
</template>
ref获取dom节点
<script setup>
import { ref ,getCurrentInstance,nextTick} from 'vue'
import Header from './Header.vue'
const {proxy} = getCurrentInstance()
const rename = ref(null)//声明一个和ref一样的名字,直接获取它
nextTick(()=>{
console.log(rename.value)
//console.log(proxy.$refs.rename) 或者直接这样获取
//要获取子组件的dom节点,通过绑定ref在子组件标签上,子组件获取自己的dom节点,通过defineExpose暴露给父组件
})
</script>
<template>
<div ref="rename"></div>
<Header/>
<div></div>
</template>