论vue组件传值之$attrs
一、当前为祖父组件,传值方式还是按照之前的传值方式一样。
<template>
<div>
<p>数字:{{ money }}</p>
<p>城市:{{ city }}</p>
<Test :city="city"></Test>
</div>
</template>
<script>
import Test from "./Test";
export default {
name: "HelloWorld",
components: {
Test
},
// 方式1
// provide: {
// name: "今天学习的新技术"
// },
// 方式2
provide() {
return {
userInfo: "优化provide"
};
},
data() {
return {
money: 100,
city: "shanhai",
message: "hello"
};
}
};
</script>
<style scoped lang="scss"></style>
二、父组件接受方式为
**这个地方最为重要的是v-bind="
a
t
t
r
s
"
∗
∗
只
有
在
这
个
地
方
写
了
v
−
b
i
n
d
=
"
attrs"**只有在这个地方写了v-bind="
attrs"∗∗只有在这个地方写了v−bind="attrs"才可以用$attrs.你的接受值的Key得到value
<template>
<div>
<p>attrs:{{ $attrs.city }}</p>
<ChildTest v-bind="$attrs">
<p>你好呀</p>
</ChildTest>
</div>
</template>
<script>
import ChildTest from "./ChildTest";
export default {
name: "Test",
// inject: ["name"],
inject: ["userInfo"],
components: {
ChildTest
},
props: {
message: {
type: String
}
},
data() {
return {};
},
mounted() {
console.log("============>>>>>", this.userInfo);
}
};
</script>
<style scoped lang="scss"></style>
三、你的值还是照常props传递过来,只不过用$attrs的方式来展现,如下代码
<template>
<div style="color:red;">
attrs的测试:{{ $attrs.city }}
<slot></slot>
</div>
</template>
<script>
export default {
props: {
message: {
type: String
}
},
data() {
return {};
}
};
</script>