用vue也有两年的时间了,今天总结下平时项目中用到的最多的组件之间的参数传递的几种方式吧~~
第一种:props && emit (父子之间参数传递)
这种方式相信大家肯定不陌生了,官方文档指定传参方式,用法不多做介绍,官网看下即可。
第二种:$bus
这种的话,对于兄弟组件用起来可能比较酸爽,因为全局广播,任一组件都是可以监听的到的。
第三种:vuex
状态管理也不做多说了,官网写的很详细,关于结构、模块化啥的,看看就ok了。
主角就是我要说的第四种,这种是vue 2.4+引进的。
其实解释起来很简单,就是当我们给一个组件传入attrbuite时候,如果组件不设置props接受,我们可以在组件上绑定$attrs属性,类似于
v-bind="$attrs",这样该组件就可以拿到$attrs这个对象,是不是有点类似于props的感觉,下面贴一段代码解释下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>$attrs</title> </head> <body> <div id="app"> <base-input label="姓名" class="name-input" placeholder="请输入姓名" v-bind="$attrs" name="xinxin" age="18" sex="man"></base-input> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script> Vue.component("base-input", { inheritAttrs: true, //此处设置禁用继承特性 props: ["label"], template: ` <label> {{label}}- {{$attrs}}- <input v-bind="$attrs"/> </label> `, mounted: function () { console.log(this.$attrs); } }); const app = new Vue({ el: "#app" }); </script> </body> </html>
标签: $attrs
还木有评论哦,快来抢沙发吧~