Vue3封装技巧(一)组件之间的传值
用了很久一段时间Vue3+Ts了,工作中对一些常用的组件也进行了一些封装,这里对封装的一些方法进行一些简单的总结。
1.props传递
首先在主组件进行定义传值
1 2 3 4 5 6 7 8 9 10 11
| <template> <div> 这里是主组件 <common :first="first"></common> </div> </template>
<script setup lang="ts"> import common from './common.vue'; import {ref} from 'vue' const first=ref('传入通用组件的值')
|
代码中common是定义的要封装的组件,这里first即是要传入的值
然后子组件要进行接收传来的值,如下
1 2 3 4 5 6 7 8 9 10 11 12 13
| <template> <div> 这里是通用组件 {{ props.first }} </div> </template>
<script setup lang="ts">
const props=defineProps({ first:String }) </script>
|
这里与vue2不同的是需要利用defineProps进行参数的接收,我这里用到了TS,所以也加入了类型声明。
2.监听参数变化
在一些业务中,父组件传给子组件的数据有时候是动态的,这个时候就需要对参数的改变进行识别了
这里就用到watch了
1 2 3 4 5 6 7 8 9
| watch( props, (newVal) => { console.log(props,'props改变了'); }, { immediate: true, } );
|
对props进行监听,如果进行改变,然后怎么进行操作,可以更细节的处理了。
这里watch的使用可以参考官网https://cn.vuejs.org/api/reactivity-core.html#watch
3.触发事件
子向父亲传递信息,或者使用父亲的方法应该怎么做呢,这是就是用到emits了
首先父组件对子组件绑定方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> 这里是主组件 <common :first="first" @getValue="getValue"></common> //这里的@就是绑定的方法 </div> </template>
<script setup lang="ts"> import common from './common.vue'; import {ref} from 'vue' const first=ref('传入通用组件的值') const getValue=(val:string)=>{ console.log(val); } </script>
|
绑定后需要在子组件进行接收
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <template> <div> 这里是通用组件 {{ props.first }} </div> </template>
<script setup lang="ts">
const props=defineProps({ first:String }) const emits=defineEmits(['getValue']) watch( props, (newVal) => { console.log(props,'props改变了'); emits('getValue','我触发了') }, { immediate: true, } ); </script>
|
这里在子组件定义接收后,再触发时用emits(’方法名’,传递参数)的形式进行触发,而这个传递参数是你在父组件绑定方法中所定义的参数。
4.调用子组件方法
在封装中,也会遇到一些调用子组件的方法,我现在常用的是下面这种
先用defineExpose将方法进行暴露
1 2 3 4 5 6
| const out=(val:string)=>{ console.log('我是子组件的方法',val); } defineExpose({ out, });
|
然后在父组件使用ref绑定子组件,获取其方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div> 这里是主组件 <common :first="first" @getValue="getValue" ref="Common"></common> </div> </template>
<script setup lang="ts"> import common from './common.vue'; import {ref,onMounted} from 'vue' const first=ref('传入通用组件的值') const getValue=(val:string)=>{ console.log(val); } const Common=ref() onMounted(() => { Common.value.out('传给你') }); </script>
|
这里就是先用ref绑定,然后利用其调用方法,括号内的参数即在子组件定义参数。
5.插槽
插槽方法可以见我以前总结的内容,这里不再详细讲解
https://blog.csdn.net/qq_49907632/article/details/127575530?spm=1001.2014.3001.5502
6.总结
上述内容其实就是对常用的组件传值进行的一个总结,真实内容封装其实还是要看组件的具体需求,但是都可能是对这些传值进行的一个应用,后续如果对封装有进一步了解,会进一步补充,敬请期待。。。