Vue自定义组件-事件使用

<!-- 组件 -->
<template>
  <button @click="btnClickEvent">
    <!-- 插件属性 -->
    <slot name="icon"></slot>
    <span>{{ msg }}</span>
  </button>
</template>

<script>
export default {
  props: {
    msg: {
      default: '下载'
    }
  },
  methods: {
    btnClickEvent: function () {
      // 执行统一事件
      console.log(this.msg)
      // 触发父组件自定义事件
      this.$emit('myClick')
    }
  }
}
</script>
组件使用
<template>
  <div id="myButton">
    <ex-btn v-on:myClick="doSth1" v-bind:msg="msg1"></ex-btn>
    <ex-btn v-on:myClick="doSth2" v-bind:msg="msg2"></ex-btn>
    <ex-btn v-on:myClick="doSth3" v-bind:msg="msg3">
      <img slot="icon" class="ico" src="@/assets/img/setting.png" />
    </ex-btn>
  </div>
</template>
<script>
import btn from '../../components/demo/button.vue'
export default {
  name: 'myButton',
  components: {
    'ex-btn': btn
  },
  data: function () {
    return { msg1: '变量1', msg2: '变量2', msg3: '变量3' }
  },
  methods: {
    doSth1: function () {
      console.log('方法1')
    },
    doSth2: function () {
      console.log('方法2')
    },
    doSth3: function () {
      console.log('方法3')
    }
  }
}
</script>

Bookmark the permalink.

Comments are closed.