vue之mixins使用

1.简介

1.1 官方简介

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

1.2个人理解

程序的本质就是辅助人来做事情,能有代码实现的,坚决不手动实现,例如,假如每个页面都用到的一个方法,每个页面都复制一份使用,极大的浪费时间精力,mixins 就是为了解决这个问题(不仅仅是方法)。

2. 使用

代码实例如下 混入有两种 全局 和 局部

// mixins.js
export default {
    components: {
    },
    created(){
    },
    methods:{
    // 公用的方法
      handleAdd(){
        this.$store.dispatch('home/addAge')
      },
      aaa(){
        console.log('aaa')
      },
      bbb(){
        console.log('bbb')
      },
      ccc(){
        console.log('ccc')
      },
    }
}

// main.js 引入
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import mixin from './mixin'

Vue.config.productionTip = false

// 混入
Vue.mixin(mixin)

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

2.1 验证是否成功

直接在页面上调用混入的方法, 能出结果就是成功了

<template>
  <div id="app">
    <h1>{{name}}</h1>
    <h1>{{age}}</h1>
    <button @click="handleAdd">点击</button>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'App',
  components: {
  },
  created(){
    this.aaa() // aaa
  },
  methods:{
  },
  computed:{
    ...mapState('home', ['name', 'age'])
  }
}
</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>

2.2 局部使用

<template>
  <div id="app">
    <h1>{{name}}</h1>
    <h1>{{age}}</h1>
    <button @click="handleAdd">点击</button>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import mixin from './mixin'

export default {
  name: 'App',
  mixins:[mixin], // 混入
  components: {
  },
  created(){
    this.aaa()
  },
  methods:{
    handleAdd(){
      this.$store.dispatch('home/addAge')
    }
  },
  computed:{
    ...mapState('home', ['name', 'age'])
  }
}
</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>

欢迎点赞、评论、关注

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子羡爱学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值