一.父组件向子组件传值
即父组件通过属性的方式向子组件传值,子组件通过 props 来接收。
// 父组件
<user-detail :myName="name" />
export default {
components: {
UserDetail
}
......
}
子组件中使用props(可以是数组也可以是对象)接收即可。可以传多个属性。
// 子组件
export default {
props: ['myName']
}
/*
props: { myName: String } //这样指定传入的类型,如果类型不对会警告
props: { myName: [String, Number] } // 多个可能的类型
prosp: { myName: { type: String, requires: true } } //必填的的字符串
props: {
childMsg: {
type: Array,
default: () => []
}
} // default指定默认值
如果 props 验证失败,会在控制台发出一个警告。
*/
基于 vue 的单向数据流,即组件之间的数据是单向流通的,子组件是不允许直接对父组件传来的值进行修改的,所以应该避免这种直接修改父组件传过来的值的操作,否则控制台会报错。
二.子组件向父组件传值
子组件绑定一个事件,通过 this.$emit() 来触发
在子组件中绑定一个事件,并给这个事件定义一个函数
// 子组件
<template>
<view>
<view>我是子组件</view>
<button type="default" @click="tip('ff')">点击 </button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
created() {
console.log("执行了吗");
this.$emit("tip","传给父组件的值");
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
我是父组件
// 父页面
<template>
<view class="content">
<custom-chidren @tip="parent"></custom-chidren>
</view>
</template>
<script>
import chidren from "../../componet/chidren.vue";
export default {
components:
{"custom-chidren":chidren}
,
data() {
return {
title: 'Hello'
}
},
methods: {
parent(res){
console.log("子组件触发了方法,然后传递给父组件",res);
}
}
}
</script>
<style>
</style>
通过回调函数进行子向父亲传值
子组件
<template>
<view>
<view>我是子组件</view>
<button type="default" @click="tip('ff')">点击</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
props:{
callback: Function,
},
created() {
console.log("执行了吗");
this.$emit("tip","传给父组件的值");
this.$props.callback("调用父亲传过来的callback")
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
父组件
<template>
<view class="content">
<custom-chidren @tip="parent" :callback="callbacktest"></custom-chidren>
</view>
</template>
<script>
import chidren from "../../componet/chidren.vue";
export default {
components:
{"custom-chidren":chidren}
,
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
callbacktest(res){
console.log("callbacktest",res)
},
parent(res){
console.log("子组件触发了方法,然后传递给父组件",res);
}
}
}
</script>
<style>
</style>
parent、children、refs访问对象
- parent获取父级
- chidren获取子级
- refs 指定获取 标签上使用ref=“aaa” 使用 this.$ref.aaa
使用vuex
请看vuex专题