1.setup
把之前.vue文件中 script 标签添加 setup 标识,这样就可以直接在使用 composition API,并且无需return 创建的响应式数据。
<script> --> <script setup>
<template>
<div>{{ hello }}</div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, computed } from 'vue'
const hello = ref('你好!')
</script>
2.getCurrentInstance 访问项目已有插件
例如项目升级之前引入的是 element UI,可以使用 getCurrentInstance 获取到的实例, 相当于之前:
this.$message.success('123') === getCurrentInstance().proxy.$message.success('123')
<template>
<el-form ref="myForm"></el-form>
</template>
<script setup>
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance().proxy // 获取实例
const message = instance.$message // elm 提示框
message.success('保存成功')
const myForm = instance.$refs.myForm
</script>
3.reactive、ref
ref: 用于声明基础类型
reative: 声明复杂类型,声明的对象需要添加值的话,外部再包一层
<template>
<div>
{{ obj }}
<button @click="demo1">demo1</button>
<button @click="demo2">demo2</button>
<button @click="demo3">demo3</button>
<button @click="demo4">demo4</button>
<button @click="demo5">demo5</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
// ref
const str = ref('你好!')
const num = ref(123)
const bool = ref(true)
// reactive
const obj = reactive({
data: {
a: '',
},
info: []
})
const demo1 = () => {
obj.data.a = 123
console.log('数据层和渲染层都成功改变', obj)
}
const demo2 = () => {
obj.info.push(1)
console.log('数据层和渲染层都成功改变', obj)
}
const demo3 = () => {
obj.data2 = { 1: 'a' }
console.log('数据层成功改变,渲染层不变,因为reactive创建obj时并没有创建data2,所以并不会双向绑定', obj)
}
const demo4 = () => {
obj.info.push(1)
obj.data2 = { 1: 'a' }
console.log('数据层和渲染层都成功改变,reactive改变值时并添加新的proxy', obj)
}
const demo5 = () => {
obj.data.a = 123
obj.data2 = { 1: 'a' }
console.log('数据层和渲染层都成功改变,reactive改变值时并添加新的proxy', obj)
}
// reactive 外部再加一层,只创建一个box,在box里增删改查都没问题
const obj = reactive({
box: {
data: {
a: '',
},
info: []
}
})
</script>
4.defineProps、 defineEmits、 defineExpose 都不需要 import 导入
<template></template>
<script setup>
// 直接使用
// 接收父组件参数
const props = defineProps({
typelist: Array
})
console.log('直接使用', typelist)
// 声明需要使用的广播
const $emit = defineEmits(['open', 'close'])
$emit('open')
// 暴露方法给父组件 - 子组件
defineExpose({
open,
})
// 使用子组件方法 - 父组件
const instance = getCurrentInstance().proxy // 获取实例
instance.$refs.Dialog.open(item.id)
</script>