pops传值
耐心五分钟,,学会vue组件通信的父传子
父组件
<template>
<div style="width: 600px;height: 600px;background-color: #000;color: #FFFFFF;">
<h1> {{ fatherMsg }} </h1>
<h1> {{ fatherMessage }} </h1>
<!-- 这边在子组件v-bind绑定你要传递去子组件中的数据 -->
<oni-gang :dataOne='fatherData' :dataTwo='fun1()'></oni-gang>
<!-- v-bind:子组件接收时的名字 = '父组件中的数据',父组件中的数据不必须是变量,
也可是函数、三元表达式等 -->
</div>
</template>
<script>
// 映入组件可自定义名字jj
import oniGang from '../../components/oni-gang/oni-gang.vue'
export default {
components: {
oniGang
},
name: 'gebuki',
data() {
return {
fatherMsg: 'gebuki',
fatherMessage: '这是父组件',
fatherData:'父组件的data',
}
},
methods: {
fun1(){
return '我是数据'
},
}
}
</script>
<style lang="scss">
</style>
子组件
<template>
<div style="background-color: #409EFF;margin-top: 100px;">
<h1>{{ childMsg }}</h1>
<h2>{{ childMessage }}</h2>
<h2>{{ dataOne }}</h2>
<h2>{{ dataTwo }}</h2>
</div>
</template>
<script>
export default {
name: 'oniGang',
props:['dataOne','dataTwo'],
// 子组件中通过props接收数据,上面这样,数组形式
data() {
return {
childMsg: 'voni-gang',
childMessage: '这是子组件'
}
},
methods: {
}
}
</script>
<style lang="scss">
</style>
结果,父组件的数据成功传递到子组件去了,
props验证
父组件
<template>
<div style="width: 600px;height: 600px;background-color: #000;color: #FFFFFF;">
<h1> {{ fatherMsg }} </h1>
<h1> {{ fatherMessage }} </h1>
<!-- 这边在子组件v-bind绑定你要传递去子组件中的数据 -->
<oni-gang :dataOne='fatherData' :dataTwo='fun1()'></oni-gang>
<!-- v-bind:子组件接收时的名字 = '父组件中的数据',父组件中的数据不必须是变量,
也可是函数、三元表达式等 -->
</div>
</template>
<script>
// 映入组件可自定义名字jj
import oniGang from '../../components/oni-gang/oni-gang.vue'
export default {
components: {
oniGang
},
name: 'gebuki',
data() {
return {
fatherMsg: 'gebuki',
fatherMessage: '这是父组件',
fatherData:'父组件的data',
}
},
methods: {
fun1(){
return '我是数据'
},
}
}
</script>
<style lang="scss">
</style>
子组件,type,默认值规则等都可以自定义函数,还可以通过validator自定义验证规则,
详细前往Prop — Vue.js
<template>
<div style="background-color: #409EFF;margin-top: 100px;">
<h1>{{ childMsg }}</h1>
<h2>{{ childMessage }}</h2>
<h2>{{ dataOne }}</h2>
<h2>{{ dataTwo }}</h2>
<h2>{{ dataThree.name }}</h2>
</div>
</template>
<script>
export default {
name: 'oniGang',
// props:['dataOne','dataTwo'], 需要验证的话就写对象形式
props:{
dataOne:{
type:String, // 规定类型
required: true // 是否必填
},
dataTwo:{
type:[String,Number], // 可以规定为多个类型,满足一个即可
},
dataThree:{
type:Object,
default:{ // 父组件没有传过来这个值,所以是没有这个值的,但是可以规定一个默认值,
// 在没有值的情况下就是默认值
name:'大坏蛋'
}
}
},
data() {
return {
childMsg: 'voni-gang',
childMessage: '这是子组件'
}
},
methods: {
}
}
</script>
<style lang="scss">
</style>
结果,