Vue3.0中暴露变量需要return出来,这样template中才能使用,这样用起来极为不方便。
Vue3.2中的一个新语法糖,在setup函数中,所有的ES模块导出都被认为是暴露给上下文的值,并包含在setup()返回对象中,相对于之前的写法,语法变得简单。
<script setup>
...
</script>
<tempalte>
<Test/>
<div>1234</div>
// vue2中template标签中只能有一个根元素,vue3中没有此限制
</template>
<script setup>
import Test from 'Test.vue'
// 引入的组件直接使用,不用通过Components进行注册,并且无法指定当前组件的名字,他会自动以文件名为主。不用再写name属性了,如果需要定义类型的name,在平级加一个script标签,在里面实现即可
</script>
<script setup>
import { defineProps, defineEmits, useSlots, useAttrs } from 'vue';
// props:通过defineProps指定当前props类型,获取上下文的props对象
const props = defineProps({ name: String })
// emits:使用defineEmit定义当前组件含有的事件,并通过返回上下文去执行emit
const emit = defineEmits(['change', 'delete'])
// 获取slots
const attrs = useAttrs()
// 获取attrs
const slots = useAttrs()
</script>
setup中定义的属性和方法无序返回,可以直接使用
setup相当于是一个闭包,除了内部的template模板,谁都不能访问内部的数据和方法,如果要对外暴露,则需要使用defineExpose API
<template>
<span>{{name}}<span>
<button @click="changeName('哈哈哈')">改变name</button>
</template>
<script setup>
import { defineExpose, reactive, ref, toRefs, computed, watch } from 'vue'
const name = ref("粉刷匠"); // ref声明响应式数据,声明基本数据类型
const state = reactive({name:'粉刷匠', sex:'男'})
const { name, sex } = toRefs(state); // toRefs解构数据,结构出来的数据可以直接使用
// 声明method方法
const changeName = (val) =>{
state.name = val
}
const nameSex = computed(()=>{
return name + '-' + sex;
})
console.log(nameSex.value) // 粉刷匠-男
// 监听
watch(()=>state.name, (newVal, oldVal)=>{
console.log(state.name, newVal, oldVal);
},{
immediate: true, // 立即执行
deep: true // 深度监听
})
// 将内部的方法抛出,父组件可以直接用
defineExpose({
name,
changeName
})
</script>
父组件
<template>
<child name="粉刷匠"/>
</template>
<script setup>
import child from './child.vue'
</script>
子组件
<template>
<span>{{name}}</span>
</template>
<script setup>
// defineProps在script setup中自动可用,无需导入。在.eslintrc.js文件中globals下配置defineProps:true
const props = defineProps({
name:{
type:String,
default:''
}
})
</script>
父组件
<template>
<child name="粉刷匠"/>
</template>
<script setup>
import child from './child.vue'
import { reactive } from 'vue'
const state = reactive({name:"粉刷匠"})
// 接受子组件方法
const updateName = (name) =>{
state.name = name;
}
</script>
子组件
<template>
<span>{{name}}</span>
<button @click="changeName">改名</buttom>
</template>
<script setup>
// defineEmits在script setup中自动可用,无需导入。在.eslintrc.js文件中globals下配置defineEmits:true
const props = defineProps({
name:{
type:String,
default:''
}
})
const emit = defineEmits(['updateName']);
const changeName = ()=>{
emit('updateName','粉刷匠2');
}
</script>