这里说一说setup语法糖和setup函数的区别?
setup函数这种写法会让外部拿到内部的数据方法,会打破单向数据流。(除非使用expose()函数)
//父组件
<template>
<div> 父组件
<MyZujian ref="myzujian"/>
</div>
</template>
<script setup>
import { ref,onMounted } from 'vue'
import MyZujian from '@/components/Zujian.vue'
const myzujian = ref(null)
onMounted(()=>{
console.log("a:",myzujian.value.a)
console.log("b:",myzujian.value.b)
})
</script>
//子组件写法一(推荐)
<script setup>
import {ref} from 'vue'
const a = ref(1)
const b = ref(2)
//defineExpose({a,b})
</script>
底下方法也是一样的暴露
//需要哪个暴露哪个
<script setup>
import {ref} from 'vue'
const a = ref(1)
const b = ref(2)
defineExpose({a,b})
</script>
//子组件写法二
<script>
import {ref} from 'vue'
export default {
setup() {
const a=ref(1)
const b=ref(2)
return {
a,
b } }}
</script>
跟setup语法糖一样的效果
//写法三 子组件
<script>
import {ref} from 'vue'
export default {
setup(props,{expose}) {
const a=ref(1)
const b=ref(2)
expose()
return {
a,
b } }}
</script>
//子组件写法四 只暴露a,不暴露b
<script>
import {ref} from 'vue'
export default {
setup(props,{expose}) {
const a=ref(1)
const b=ref(2)
expose({a})
return {
a,
b }}}
</script>
v-model可以在组件上实现双向绑定并且在v3.4开始,推荐使用defineModel宏来实现
const 名字 = defineModel('参数名',options) //简写也可以省略参数名,修饰符,这里不需要参数
const [名字,名字Modifiers] = defineModel('参数名',options) //修饰符特定写法
举例:const [ count ,countModifiers] = defineModel('参数名',options)
//countModifiers为修饰符
options={
type: Number, //类型
default: 0, //默认值 ***如果父组件没传值,这里应用了会导致不同步
required: true //是否必须传值
}
//父组件
<template>
<div>
<h1>父组件的值:{{ count }}</h1>
<MyZujian v-model="count"/>
</div>
</template>
<script setup>
import MyZujian from './components/Zujian.vue'
import { ref } from 'vue'
const count = ref(0)
</script>
//子组件 defineModel() 返回的值是一个 ref。
<template>
<div>
<h1>子组件的值:{{ modelValue }}</h1>
<button @click="modelValue++">change</button>
</div>
</template>
<script setup>
const modelValue = defineModel()
</script>
修饰符(可以自定义修饰符逻辑)
//父组件
<template>
<div>
<MyZujian v-model:title.trim="count"/>
</div>
</template>
<script setup>
import MyZujian from './components/Zujian.vue'
import { ref } from 'vue'
const count = ref(0)
</script>
//子组件
<script setup>
const [count ,countModifiers] = defineModel('title')
console.log(countModifiers)
</script>