在 vue 项目中: 父子组件之间的传化值是避免不了的。
1: 父组件向子组件传值:
父组件向子组件传值: 使用props 属性
父组件:
<template> // 模板区域
<div>
// 子组件
<sidebar-item :data-reactive= "transmitData"></sidebar-item>
</div>
</template>
<script>
// 导入子组件
import sidebar-item form './sideBarItem.vue';
export default {
// 注册组件
components: {
sideBarItem, // 可以注册多个组件
},
data() {
transmitData:{
name: 'xxxx',
age: 18,
}
},
}
</script>
---------------------------------------------------------
在子组件中定义一个指令: (自定义指令: 自定义指令的值与子组件中, props中属性中值保持一致)
子组件:
<script>
name: 'sideBarItem',
props: {
type: Object,
default: null
}
</sctipt>
注意在: 在子组件中定义props 属性, transmitData 类型可以是自定义类型(但是必须和父组件的数据类型一致, 否则就会报错, default:为默认值)
2: 子组件向父组件传递数据:
// 子组件向父组件传递数据: 使用$emit 方法:
子组件 child.vue 文件
<template>
<div class="test">
<input type="text" v-model="message" />
<button @click="click">发送给父组件</button>
</div>
</template>
<scirpt>
export default {
data() {
return {
message: '来自子组件的数据'
}
}
methods: {
click() {
this.$emit('childFn', 'this.message'); // 第一个参数事件名称, 第二个参数需要传递参数
// childFn 组件的方法名称, 父组中用 childFn 来接受子组件的数据, message: 是需要传递的参数
}
}
}
</script>
---------------------------------------------------------
父组件方法:
定义父组件:
<template>
<div>
<child-com @childFn="parentFn"></child-com>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
parentFn(childData) {
this.message = childData;
}
}
}
</script>
// 1: 父组件中注册子组件
// 2: 定义方法childFn (必须和子组件中方法名一致, ) parenFn: 定义可以是随意的。
// 3: 大型项目如果使用两种以上的传值方法, 耦合性大。 所以大型项目的话,还是要使用vuex 进行状态管理。