vue3的一些基本常识(slot,ref)
slot:
vue3推荐v-slot的写法,类似@和:v-slot也可以简化为#符号,demo如下:
子组件写法不变:
<template> <div> hello: <slot name="fruits" :fruitsName="obj.name" :freshness="obj.freshness"> </slot> </div> </template> <script setup lang="ts"> import { reactive } from "@vue/reactivity"; const obj = reactive({name:'桃子',freshness:5}) const setName = (name:string)=>{ obj.name = name } /** * 要对父组件暴露的方法和属性必须都写到defineExpose中,不然获取不到 */ defineExpose({obj,setName}) </script> <style lang='scss' scoped> </style>
父组件:
<template>
<div>
<navList ref="navlistRef">
<!-- #fruits相当于v-slot:fruits等号后面的东西相当于vue2的slot-scope -->
<template #fruits="obj">我是水果1号,{{JSON.stringify(obj)}}</template>
</navList>
<button @click="navlistChange">改你的水果一号</button>
{{num.name}}
</div>
</template>
<script setup lang="ts">
import { ref,toRefs} from 'vue';
import navList from './components/NavList.vue'
/**
* ref的写法是给原对象创建了一个副本(拷贝),修改后不会影响原对象的值,但是对象类型的做了ref操作后会简历reactive的响应式,这时候更改了ref的对象的属性值会影响原对象。ref会让UI从新渲染
*/
const navlistRef = ref<{obj:{name:string,freshness:number},setName:Function}|null>()
/**
* torefs的写法修改后会影响原对象,因为是引用的之前的对象的地址,但是这是响应式的,修改后UI不变
*/
let num = toRefs({name:'zs',sex:14})
var resource = {other:{sex:1},address:'大道西侧'}
const info = toRefs(resource)
var resource1 = {name:'zds'}
const info1 = ref(resource1.name)
const navlistChange=()=>{
//子组件的属性依然不可以去修改
navlistRef.value?.obj?.name;
num.name.value='12'
//但是可以通过调用子组件的方法修改子组件的属性
navlistRef.value?.setName('葡萄')
info.other.value.sex=2
info.address.value="大道东侧"
console.log(resource,resource1)
info1.value='lsd'
debugger
}
</script>
<style lang='scss' scoped>
</style>
积累小的知识,才能成就大的智慧,希望网上少一些复制多一些原创有用的答案

浙公网安备 33010602011771号