通常情况下,我们都是都是直接使用 v-bind:value=“value” 或者 :value=“value”,这种写法没有问题。 就好比下面的写法
<template> <your-component :name="name" :sex="sex" :age="age" :address="address" /> </template> <script> export default { data(){ return { name:"", sex:"", age:"", address:"" } } } </script>上面的是常规的写法。 如果存在下面的场景,我们应该怎么办呢? 1、prop入参很多,怎么写更好维护? 2、该组件发生嵌套的时候,怎么保证拓展性,易用?
首先我们需要弄清楚v-bind这个指令到底做了什么? v-bind:name=“name” 就是在对应的标签内声明了一个行内属性 name=name (当前实例中的name); v-bind="{name,age,sex}" 相当于同时声明三个属性,:name=“name”,:age=“age”,:sex=“sex”;也就是说上面代码可以改写成
<template> <your-component v-bind="{name,age,sex,address}" /> </template> <script> export default { data(){ return { name:"", sex:"", age:"", address:"" } } } </script>结论: 1、v-bind="{}“可以帮助我们同时进行多个属性传值; 2、v-bind=“function(){reutrn {}}”,可以是工厂函数,可以来批量处理用户入参; 3、结合v-bind=”$attrs",可以实现组件多次封装嵌套;
$attrs是不在prop中已经的定义的其他属性集合 结合上面的 your-component来,如果 your-component 的prop定义了 [“name”,“age”],那么 your-component 的 a t t r s = s e x : " " , a d d r e s s : " " , 可 以 在 y o u r − c o m p o n e n t 中 c o n s o l e . l o g ( t h i s . attrs = {sex:"",address:""},可以在 your-component 中 console.log(this. attrs=sex:"",address:"",可以在your−component中console.log(this.attrs) 进行查看。