父传子
在父组件中,用v-bind动态绑定一个自定义属性,用于给子组件传递数据
<template>
<son :user="user"></son>
</template>
<script>
import son from "./son.vue"
export default {
components: { son },
data() {
return {
user:'张三'
}
}
}
</script>
在子组件中,使用 props 接收父组件传过来的数据。
<template>
<view>{{ user }}</view>
</template>
<script>
export default {
data() {
return {
}
},
props: ["user"],
}
</script>
子传父
子组件通过事件的方式,利用 $emit 给父组件传值。
注意:$emit 的第一个参数是父组件自定义事件的方法名,后边的 “value” 是子组件要给父组件传递的数据
<template>
<view>
<button @click="click">{{ user }}</button>
</view>
</template>
<script>
export default {
data() {
return {
user: "张三"
}
},
methods: {
click() {
this.$emit("info", this.user);
}
}
}
</script>
在父组件中,绑定一个自定义事件,用来接收子组件传来的值。
<template>
<son @info="getInfo"></son>
</template>
<script>
import son from "./son.vue"
export default {
components: {
son
},
data() {
return {
}
},
methods: {
getInfo(value) { // value 就是子组件传递过来的数据
console.log(value)
}
}
}
</script>