vue组件间的参数传递

场景分析

在前端开发中,咱们经常会运用到“组件库”。在main入口中引入组件库,就能够很轻松的在页面中引入,并作一些基本的配置,如样式,颜色等。只须要在引入的组件中写入特定的属性,就可以定义。html

举例说明

例如: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咱们在之后的文章中会讲到,就是“抛出事件”。vue

这就分为组件的最基本功能:element-ui

  • 数据进
  • 事件出

那组件的使用咱们知道了,经过active-color传入参数,经过@来接收事件。
因此,咱们来探究一下组件的内部结构是什么样的?函数

我写了一个小模型,是一个显示标题的小按钮,经过div包裹。ui

<!-- 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>

使用方法:this

<!-- 父组件使用 -->
<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接收父组件传递过来的数据,经过工厂函数获取一个默认值。code

传递

经过this.$emit('ai_click', title)告诉父组件,我要传递一个事件,名字叫“ai_click”,请经过@ai_click接收一下,而且我将title的值返回父组件。component

总结

因此今天分析vue组件的3大核心概念的其中两个——属性和事件。
这篇文章只分析到应用场景,也是最简单的组件。但愿后续可以深刻了解vue的组件概念:属性、事件和插槽。htm

相关文章
相关标签/搜索