vue基础 子、父级相互传值
父传子 1.父组件
<template>
<div>
<HelloWorld :msg="msg" v-model="number"></HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
components:{
HelloWorld
},
data() {
return {
msg:"欢迎使用vue",
//默认值2
number: 2
}
},
}
</script>
子组件:
<template>
<div>
<p>{{msg}}</p>
<p>{{number}}</p>
<button @click="change">number+1</button>
</div>
</template>
<script>
export default {
// 这里的model是model实时接收的数据模块,prop:是接收的属性,number是接收的变量值
model:{
prop:"number",
event:"aa" //定义用于传值的事件名
},
props: {
msg:String,
number:Number
},
methods:{
change(){
// 调用event定义的传值的变量aa
this.$emit("aa",this.number+1)
}
}
};
</script>
子组件另外一种写法
<template>
<div>
<p>{{msg}}</p>
<!-- <p>{{number}}</p> -->
<p>{{value}}</p>
<button @click="change">number+1</button>
</div>
</template>
<script>
export default {
//model: {
// prop: "number", //变量名
// event: "aa" //自定义的事件名
//},
props: {
msg: String,
value: Number //接收number,N必须要大写
},
methods: {
change() {
// this.$emit("aa", this.number + 1);
this.$emit("input", this.value + 1); //必须使用默认的input事件进行变量更改提交
}
}
};
</script>
2.父传父
子组件,这个利用直接赋值传递,msg的数据也可以来源于vdata的传递
<template>
<div>
<child msg="一条消息"></child>
</div>
</template>
<script>
import child from './child'
export default {
components:{
child
}
}
</script>
子组件
<template>
<div>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
props: ["msg"]
};
</script>
本文章代码参考于https://www.cnblogs.com/KlllB/p/10500479.html ,仅仅是学习参考使用

浙公网安备 33010602011771号