父传子需要注意的点是:
1、需要先在<template>中自定义一个组件<comp-z>,然后再绑定一个自定义属性名:msg2:'msg',比如:
<comp-z :msg2.sync="msg" ref="compd"></comp-z>
2、接着我们在父组件data中写属性的值,并return出去
data() {
return {
msg: "我来自父组件",
};
},
3、父组件的完整写法:
<template>
<div>
<h1>father组件</h1>
<h2 ref="h2">{{ msg }}</h2>
<!-- sync语法糖-可以少写一个change -->
<!-- :msg2动态绑定一个自定义属性名或者是固定属性 -->
<comp-z :msg2.sync="msg" ref="compd"></comp-z>
</div>
</template>
<script>
// 引入组件
import compZ from "./components/compZ.vue";
// 默认导出
export default {
name: "App",
components: {
compZ,
},
data() {
return {
msg: "我来自父组件",
};
},
mounted() {
this.$refs.compd.tank();
console.log(this.$refs.h2);
},
};
</script>
<style>
</style>
子组件接收注意的是:
1、写一个<h1>标签接收自定义属性{{{msg2}}
<h2 @click="dian">{{ msg2 }}</h2>
2、子组件需要使用props接收msg2:
props: ["msg2"],
3、子组件的完整写法:
<template>
<div>
<h1>son组件</h1>
<h2 @click="dian">{{ msg2 }}</h2>
</div>
</template>
<script>
export default {
name: "compZ",
// props: ["msg2"], 第一种
// props:{
// msg2:String
// } , 第二种
// 第三种
props: {
msg2: {
type: String,
default: "默认值",
},
},
};
</script>