Vue mixins 复用组件功能

Vue About 1,513 words

mixins

混入(mixin) 提供了一种非常灵活的方式,来分发Vue组件中的可复用功能。

一个混入对象可以包含任意组件选项。

当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

选项合并

当组件和混入对象中的属性发生冲突时,会进行合并。

datacomputedwatch:以组件数据优先。

生命周期函数:mixins优先,组件其次。

定义 mixins

定义mixins.js文件,内容包含了Component组件的datawatchcomputed、生命周期函数等。

export default {
    data() {
        return {
            message: '混入对象',
            info: {
                username: "zhangsan",
                age: 20,
                address: null
            }
        }
    },
    computed: {
        myMixinsComputed() {
            return this.message + " my mixins computed"
        },
    },
    created() {
        console.log("mixins created")
    },
    mounted() {
        console.log("mixins mounted")
    },
    destroyed() {
        console.log("mixins destroyed")
    },

}

引用 mixins

<template>
  <div>
    <p>
      {{ message }}
    </p>
    <p>
      {{ info }}
    </p>
    <p>
      {{ myMixinsComputed }}
    </p>
  </div>
</template>

<script>
import mixins from "@/mixins/mixins";

export default {
  name: "MyMixinsComponent",
  mixins: [mixins],
  data() {
    return {
      message: "my component",
    }
  },
  created() {
    console.log("my component created")
  },
  mounted() {
    console.log("my component mounted")
  },
  destroyed() {
    console.log("my component mounted")
  }
}
</script>

输出

mixins created
my component created
mixins mounted
my component mounted

参考

https://cn.vuejs.org/v2/guide/mixins.html

Views: 1,034 · Posted: 2023-01-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh