摘要
vue的组件传值的方法有很多,今天复习的是父子组件之间的传值。至于vuex和事件总线,我们明天复习。
父组件传给子组件
这个可以说是组件传值中最容易理解的。主要使用到组件中的props属性。
1、首先在父组件中引入并使用子组件
2、定义一个变量,并绑定到子组件中
3、在子组件的props中定义一个同名变量接收父组件传递的值
首先父组件
<template>
<div class="home">
<!-- home -->
<!-- 使用子组件,并绑定msg传递给子组件 -->
<hello-world :msg="msg"></hello-world>
</div>
</template>
<script>
// @ is an alias to /src
// 引入子组件
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
// 注册子组件
components: {
HelloWorld
},
data() {
return {
msg:"父组件传给子组件的值"
}
},
}
</script>
接下来子组件
<template>
<div class="hello">
<!-- 使用父组件传递的值 -->
hello{{msg}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
// 接收父组件传递的值
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
效果:
子组件给父组件传值
子组件给父组件传值是使用发送事件的方式,然后用事件参数来传递数据的。
1、首先子组件定义事件并发送给父组件
2、父组件定义变量用来保存子组件数据;并接收子组件事件
3、在父组件中处理子组件发送的事件,并保存传过来的数据
父组件:
<template>
<div class="home">
<!-- home -->
{{msg1}}
<!-- 使用子组件,并绑定msg传递给子组件 -->
<hello-world :msg="msg" @aaa="hCli"></hello-world>
</div>
</template>
<script>
// @ is an alias to /src
// 引入子组件
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
// 注册子组件
components: {
HelloWorld
},
data() {
return {
msg:"父组件传给子组件的值",
msg1:""
}
},
methods: {
hCli(value){
this.msg1 = value;
}
},
}
</script>
子组件:
<template>
<div class="hello">
<!-- 使用父组件传递的值 -->
hello{{msg}}
<button @click="cli">点击发送事件</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
// 接收父组件传递的值
props: {
msg: String
},
data() {
return {
msg1:"子组件传递给父组件的值"
}
},
methods: {
cli(){
this.$emit("aaa",this.msg1);
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
结果(未点击时)
结果(点击后)