1.props+$emit
①父组件引用子组件,并在子组件上v-bind,绑定要传的数据,同时注册引入子组件,
子组件通过props接收父组件传过来的数据,然后通过this.$props.值来用
举例:①子接收部分props
父组件:
<template>
<div>
<div>
<div @click="father">子组件向父组件传值,父组件接收</div>
<son :weather="weatherd" ;></son>
</div>
</div>
</template>
<script>
import son from "../Father/component/son.vue";
export default {
components: { son },
data() {
return {
weatherd: "今天天气不太好",
};
},
}
子组件:
<template>
<div>
<div @click="son" style="border:1px solid red;width:300px,height:300px">
父组件向子组件传值,子组件接收
</div>
</div>
</template>
<script>
export default {
props: ["weather"],
data() {
return {};
},
methods: {
son() {
console.log(this.$props.weather);
},
}
父组件向子组件传值,子组件接收
举例②父接收部分$emit (皆为部分代码,但是用到的全有)
②以收缩按钮为例,父组件定义数据通过子组件来接收,前边同理,然后子组件定义单击响应事件,
通过this.$emit('事件名')发出去,然后在父组件中的这个子组件身上通过@事件名来操作
父组件:Home
<template>
<div class="home">
<el-container>
<el-aside width="200px" v-if="this.showAside == true">
<NavMenu></NavMenu>
</el-aside>
<el-container>
<el-header>
<LogOut
:showAside="showAside"
@onShow="showAside = !showAside"
></LogOut>
</el-header>
<el-main>
<router-view />
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
// @ is an alias to /src
import LogOut from "./component/LogOut.vue";
export default {
name: "Home",
components: {
LogOut,
},
data() {
return {
showAside: true,
};
},
methods: {
// 调用子组件的方法
},
};
子组件:LogOut
<template>
<div class="header">
<i
:class="this.showAside ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
@click="onShow"
></i>
<div class="headerPhoto">
<el-avatar :src="circleUrl"></el-avatar>
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
admin<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人中心</el-dropdown-item>
<el-dropdown-item command="exit">退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</div>
</template>
<script>
export default {
props: ["userList", "showAside"],
data() {
return {
circleUrl:
"https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
};
},
methods: {
onShow() {
this.$emit("onShow");
},
}
2.ref+$refs
父组件想要用子组件的方法 ,此时父组件已经引用了子组件,父组件只需要在子组件上用ref='要用的子组件的方法/绑定一个名字',然后通过
this.$refs.ref.'绑定的名字'.父组件需要用的方法名即可
父组件
<template>
<div>
<div>
<div @click="father">子组件向父组件传值,父组件接收</div>
<!-- <son :weather="weatherd"></son> -->
<son :weather="weatherd" ref="happy" ;></son>
</div>
</div>
</template>
<script>
import son from "../Father/component/son.vue";
export default {
components: { son },
data() {
return {
weatherd: "今天天气不太好",
};
},
methods: {
father() {
// console.log("..");
this.$refs.happy.happy();
},
},
};
子组件:
export default {
props: ["weather"],
data() {
return {};
},
methods: {
son() {
console.log(this.$props.weather);
},
// son() {
// this.$emit("son");
// },
happy() {
console.log("掌握父子传值,心情happy");
},
},
};
点击子组件向父组件传值,父组件接收
===============================================
分割线 其他方法后续补充 目前练习用到了这两个.有不对的地方感谢指正