vue $attrs的使用

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 在父组件模版中用的数据 -->
<my-button :msg="msg" :a="10" b="20"></my-button>
</div>
<script src="../01-vue-basic/code/node_modules/vue/dist/vue.js"></script>
<script>
// 组件通信 父传子
/* 根实例
let vm = new Vue({
el: "#app",
data: {
msg: "登录"
},
// 组册和挂载
components: {
"MyButton":{
data() {
return {

}
},
props:['msg','a','b'],
template: `
<button>{{msg}}{{a+1}}{{b}}</button>
`
}
}
});
*/
let vm = new Vue({
el: "#app",
data: {
msg: "登录"
},
// 组册和挂载
components: {
"MyButton":{
mounted() {
// 对没有使用的属性 保留在this.$attrs 
console.log(this.$attrs);
},
inheritAttrs:false, // 没有用到的数据 不会显示在dom结构上
data() {
return {

}
},
template: `
<div>
<my-child v-bind="$attrs"></my-child>
</div>
`,
components: {
"myChild":{
props:['msg','a','b'],
template:`
<span>{{msg}}{{a}}</span>
`
}
}
}
}
});
</script>
</body>
</html>
this.$attrs 是从父组件获取的数据,也可以通过props获取
原文地址:https://www.cnblogs.com/zhx119/p/11371592.html