本篇内容主要讲解“vue中如何实现组件间参数传递”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue中如何实现组件间参数传递”吧!
举例说明
例如:element-ui组件库中使用switch开关,有个属性active-color是设置“打开时”的背景色。change事件是触发状态的事件。
<el-switch
v-model="value"
:active-color="activecolor"
@change="touchSwitch">
</el-switch>
<script>
export default {
data() {
return {
value: true,
activecolor: '#13ce66'
}
},
methods: {
touchSwitch () {
// 这里入方法
}
}
};
</script>
分析代码
我们分析上面的代码
首先我们可以看到active-color是将特定的数据传给组件,也就是父传子组件。
其次是@change虽然监听的是改变事件,但是语法糖依然是$emit,什么emit我们在以后的文章中会讲到,就是“抛出事件”。
这就分为组件的最基本功能:
•数据进
•事件出
那组件的使用我们知道了,通过active-color传入参数,通过@来接收事件。
所以,我们来探究一下组件的内部结构是什么样的?
我写了一个小模型,是一个显示标题的小按钮,通过div包裹。
<!-- type-box.vue -->
<template>
<div class="box" @click="ai_click(title)">{{title}}</div>
</template>
<script>
export default {
name: 'type-box',
props: {
title: {
type: String,
default: () => ''
}
},
methods: {
ai_click (title) {
this.$emit('ai_click', title)
}
}
}
</script>
<style scoped>
.box{
width: 250px;
height: 100px;
margin: 10px;
border-radius: 10px;
background-color: #3a8ee6;
color: white;
font-size: 25px;
line-height: 100px;
text-align: center;
cursor: pointer;
}
</style>
使用方法:
<!-- 父组件使用 -->
<template>
<div>
<type-box title="演示盒子" @ai_click=“touch”></type-box>
</div>
</template>
<script>
import typeBox from './type-box'
export default {
components: {
typeBox
},
methods: {
touch (data) {
console.log(data)
}
}
}
</script>
分析组件
接收
通过props接收父组件传递过来的数据,通过工厂函数获取一个默认值。
传递
通过this.$emit('ai_click', title)
告诉父组件,我要传递一个事件,名字叫“ai_click”,请通过@ai_click接收一下,并且我将title的值返回父组件。
到此,相信大家对“vue中如何实现组件间参数传递”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!