你想体验新的vue写法吗
<script setup lang="ts">
// Do anything...
import {
ref,
reactive,
toRefs,
} from 'vue'
const data = reactive({
patternVisible: false,
debugVisible: false,
aboutExeVisible: false,
})
const content = ref('content') //使用toRefs解构
const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data)
</script>
- 由于 setup 不需写 return,所以直接声明数据即可,也不需要写data函数。相对应的
methods: {}也是不需要了
import { reactive } from 'vue'
const data = ref(1)
const onClickHelp = () => {
console.log(`系统帮助`)
data.value = data.value + 1
}
watchEffect -响应式 API:核心 | Vue.js (vuejs.org)
function watchEffect(
effect: (onCleanup: OnCleanup) => void,
options?: WatchEffectOptions
): StopHandle
type OnCleanup = (cleanupFn: () => void) => void
interface WatchEffectOptions {
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
type StopHandle = () => void
-
详细信息 第一个参数就是要运行的副作用函数。这个副作用函数的参数也是一个函数,用来注册清理回调。清理回调会在该副作用下一次执行前被调用,可以用来清理无效的副作用,例如等待中的异步请求 (参见下面的示例)。
第二个参数是一个可选的选项,可以用来调整副作用的刷新时机或调试副作用的依赖。
返回值是一个用来停止该副作用的函数。
<script setup>
import {
ref,
watchEffect
} from 'vue'
const count = ref(0)
watchEffect(() => console.log(count.value))
// -> 输出 0
count.value++
// -> 输出 1
</script>
watch
<script setup>
import {
reactive,
watch,
} from 'vue'
//数据
let sum = ref(0)
let msg = ref('你好啊')
let person = reactive({
name:'张三',
age:18,
job: {
name: '洗浴达人'
}
})
// 两种监听格式
watch([sum, msg],(newValue, oldValue)=>{
console.log('sum或msg变了',newValue, oldValue)
}, {immediate:true})
watch(() => person.job,(newValue, oldValue)=>{
console.log('person的job变化了',newValue, oldValue)
}, {deep:true})
</script>
computed
- 接受一个 getter 函数,返回一个只读的响应式 ref 对象。该 ref 通过
.value暴露 getter 函数的返回值。它也可以接受一个带有get和set函数的对象来创建一个可写的 ref 对象。
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // 错误
props
<template>
<span>{{props.name}}</span>
</template>
<script setup>
import { defineProps } from 'vue'
// 声明props
const props = defineProps({
name: {
type: String,
default: '11'
}
});
// const props = defineProps(['name'])
</script>
获取子组件ref变量和defineExpose暴露
- 类似react
forwordRef
<template>
<p>{{data }}</p>
</template>
<script setup>
import {
reactive,
toRefs
} from 'vue'
/** * 数据部分 * */
const data = reactive({
modelVisible: false,
historyVisible: false,
reportVisible: false,
})
defineExpose({ ...toRefs(data)})
</script>
<template>
<button @click="onClickSetUp">点击</button>
<Content ref="content" />
</template>
<script setup>
import {ref} from 'vue'
// content组件ref
const content = ref('content')
// 点击设置
const onClickSetUp = ({ key }) => {
content.value.modelVisible = true
}
</script>