watch
监听一个值:
import {ref, watch} from "vue";
const count = ref(0)
watch(count,(newValue,oldValue)=>{console.log(newValue,oldValue)
},{immediate:true,deep:true
})
监听一个对象,如果修改一个对象的属性触发watch,需要添加deep
监听多个值: 任意一个值变化都会执行
import {ref, watch} from "vue";
const count = ref(0)
const name = ref("cc")watch([count,name],([newCount,newName],[oldCount,oldName])=>{console.log(newCount,newName,oldCount,oldName)
})
精确监听对象的某个属性,,deep为true会监听对象所有属性,,有些时候只需要监听其中一个属性的变化:
import {ref, watch} from "vue";
const info = ref({name:"cc",age:20})watch(()=>info.value.age,(newValue,oldValue)=>{console.log(newValue,oldValue)
})
deep属性一旦开启,就会执行递归遍历,有一定的性能损耗,绝大多数情况下,不开启deep,使用精确侦听
生命周期函数
连续多次调用钩子函数: 会依次执行
import {onBeforeMount, onMounted} from "vue";onMounted(()=>{console.log("mounted")})
onMounted(()=>{console.log("mounted222")
})
父子通信
父传子: defineProps()
子传父:defineEmits()
<script setup>
// 编译器宏函数
const props = defineProps({message:String,hehe:String
})console.log(props)// var emit = defineEmits(["get-message"])
var emit = defineEmits(["get-message"])
const getMessage = ()=>{emit("get-message","cc")
}
</script><template>
<div>son --{{message}}</div><div> {{ props.hehe}}</div><button @click="getMessage">btn</button>
</template>
获取dom实例
ref引用组件实例,,因为默认情况下在setup
里面,组件内部的属性和方法是不开放给父组件的,如果需要开放,需要在自组件中使用defineExpose()
暴露出属性
const test = "123232"
defineExpose({test:test
})
跨层组件通信
provide提供变量和方法
inject 接收变量和方法:
底层组件可以修改顶层组件,, 使用顶层组件传递下来的函数
<script setup>
import father from "./components/father.vue"
import {provide, ref} from "vue";const count = ref(0)
provide("key",count)const add = ()=>{count.value++
}provide("add",add)
</script><template><father></father></template>
<script setup>import {inject} from "vue";const message = inject("key")
const add =inject("add")
</script><template>
son -- {{message}}<button @click="add">add</button>
</template>