这是小小的本周的第三篇,本篇将会讲解关于Element UI 父子组件传值与事件绑定。
父子组件传值
新建父组件和子组件
新建父组件
代码如下
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<ming></ming>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import ming from './components/ming.vue'
export default {
name: 'App',
components: {
HelloWorld,
ming
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
新建子组件
这里新建子组件 代码如下
<template>
<div class="hello">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
目录结构
这里设置相关的目录结构
父组件页面
在父组件添加相关的值
data(){
return{
ming: ""
}
}
在组件中进行绑定
<ming :ming="ming"></ming>
子组件页面
添加相关的值
props: {
ming: String
}
进行页面输出
<template>
<div class="hello">
Hello World
{{ming}}
</div>
</template>
效果如下
这样就完成了基本的父子组件传值
父子组件事件绑定
这里书写关于父子组件事件绑定 即,子组件调用父组件相关方法
父组件
父组件添加相关的方法
methods: {
fatherMethod() {
console.log('father组件');
},
activeSon(){
this.fatherMethod()
}
}
进行相关绑定
<ming @callFather="activeSon"></ming>
子组件进行调用
methods: {
activeBtn() {
this.$emit("callFather")
}
}
添加相关的click
<div @click="activeBtn" style="width: 300px;height: 300px;background-color: #2c3e50"> </div>
效果图
小明菜市场
推荐阅读
● 实战 | Vue + Element UI 表格组件二次封装
● 应用 | Redis实现 主从,单例,集群,哨兵,配置应用
● 实战 | GitLab + Docker 实现多环境部署