Vue Mixins(混入)使用

总结

mixins文件中定义的methods方法,可以在每个文件中引入使用,data中定义的数据,在各个文件中都是独立的,默认都是初始值,不会因为在其中一个文件中修改而修改,即方法和参数在各组件中不共享。

定义

// myMixins.js文件
export const myMixins = {
    components:{},
    data() {
        return {
            priceMixins: 66,
        }
    },
    mounted() { },
    methods: {
        // 价格加减
        priceAddRemoveMixinsEvent(type){
            if(type === 'add'){
                this.priceMixins++;
            }
            if(type === 'remove'){
                this.priceMixins--;
            }
        }
    }
}

使用tab1

// tab1.vue文件
<template>
  <div>
    tab1-Page
    <hr>
    <!-- 取的mixins中的变量 -->
    price:{{ priceMixins }}
    <hr>
    <button @click="handEvent('add')">+</button>
    <button @click="handEvent('remove')">-</button>
  </div>
</template>

<script>
import { myMixins } from "@/utils/myMixins";
export default {
  //      数组中可以引入多个mixins文件,不同文件中事件、data变量不能重复
  mixins: [myMixins,],
  methods: {
      handEvent(type){
          // 触发mixins组件的方法
          this.priceAddRemoveMixinsEvent && this.priceAddRemoveMixinsEvent(type);
      }
  },
}
</script>

使用tab2

// tab2.vue文件
<template>
  <div>
    tab2-Page
    <hr>
    <!-- 取的mixins中的变量 -->
    price:{{ priceMixins }}
    <hr>
    <button @click="handEvent('add')">+</button>
    <button @click="handEvent('remove')">-</button>
  </div>
</template>

<script>
import { myMixins } from "@/utils/myMixins";
export default {
  //      数组中可以引入多个mixins文件,不同文件中事件、data变量不能重复
  mixins: [myMixins,],
  methods: {
      handEvent(type){
          // 触发mixins组件的方法
          this.priceAddRemoveMixinsEvent && this.priceAddRemoveMixinsEvent(type);
      }
  },
}
</script>

使用App.vue

// App.vue文件
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> | 
      <router-link to="/tab1">tab1-mixins</router-link> | 
      <router-link to="/tab2">tab2-mixins</router-link>
    </nav>
    <hr>
    price-App:{{ priceMixins }}
    <hr>
    <router-view/>
  </div>
</template>

<script>
import { myMixins } from "@/utils/myMixins";
export default {
  mixins: [myMixins,],
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

&做梦的少年&

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

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

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

打赏作者

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

抵扣说明:

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

余额充值