vue2混入写法

为什么用 mixins

从官方的介绍我们可以知道

  • mixins的作用是抽取组件中相同的属性和方法到独立的文件,以便公用。
  • mixins对象会被混入该组件本身,所有会有命名冲突

举个例子:做一个公共返回顶部

因为每个页面都要写滚动的生命周期,然后再把滚动的值传到组件里

所以做了一个公共组件和一个公共专门放混入写法的文件,这样写的好处就不需要每个页面是维护,改个公共文件就行了

1.混入代码写法:

 

 返回顶部子组件:

 

 代码:

<template>
    <view>
        <view class="public-goback" @click="topBack" v-if="isShow" >返回顶部</view>
    </view>
</template>
<script>
export default {
    data() {
        return {
            isShow: false,
        };
    },
    // 接受父组件的值
    props: {
        scrollHeight: {
            type: Number,
            required: true,
        },
    },
    watch: {
        scrollHeight(val) {
            uni.getSystemInfo({
                success: (res) => {
                    // 判断滚动高度大于屏幕高度
                    this.isShow = val > res.screenHeight;
                },
            });
        },
    },
    methods: {
        topBack() {
            if (uni.pageScrollTo) {
                uni.pageScrollTo({
                    scrollTop: 0, // 滚动到页面的目标位置  这个是滚动到顶部, 0
                    duration: 300, // 滚动动画的时长
                });
            } else {
                uni.showModal({
                    title: "提示",
                    content:
                        "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。",
                });
            }
        },
    },
};
</script>
<style lang="less" scoped>
/* 返回顶部 */
.public-goback {
    position: fixed;
    left: 50%;
    transform: translateX(270rpx);
    bottom: 8%;
    z-index: 10;
    width: 90rpx;
    height: 90rpx;
    overflow: hidden;
    background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAMAAAAPdrEwAAAA/1BMVEVwcHAAAABvb29xcXFvb29ycnJycnJwcHBwcHBvb29wcHBxcXFwcHBubm5vb29ycnJ1dXVwcHBvb29vb29vb29wcHBubm5iYmJvb29wcHBxcXFubm51dXVubm5tbW1kZGRvb29wcHBvb29wcHBvb29wcHBvb29ubm5wcHBwcHB4eHhxcXFubm54eHhwcHBxcXFvb29xcXFubm5wcHBtbW1ubm5RUVFtbW1wcHBwcHBwcHBvb291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CMw39Hc0yemkRY//oAtc79cKhWUwvXdujKwjKJE1aO9659Qb2gisvSNp7BFxtj/ZpluK0d7ZJkvQh39HU1Y7162ab8LZbO6BXQMgAdeLNnZ2Fa9DTo+IdesO1yPiE7dE6ty149uje07kGuu2yGdcOLSc2LvS4FQ5GNF13J4fPw9HvPfZUPwEPDHMpu9PMvAq+59RT7F8PYwHp6U/lrvt4FkhOPqUcQ2T9w3i9oZ1w9K58wviWfC6zyYg00u+MuennNGn1SnCibOR8noE13lFuFcENq8aotIOnSko6ttgEPMpclQ0vOFothjglHeczLQABhyePmIhWhqHPdseFbqS0TxuzyMWTka4T6drHH6nL8/i5dblM9dYTRuq/n6MH6jfneEGMAyi7mgAAAABJRU5ErkJggg==")
        no-repeat;
    background-size: 100%;
    text-indent: -99999px;
}
</style>
uni.getSystemInfo这个可以获取到手机的信息,比如这里要获取屏幕的高度 res.screenHeight

父组件引用子组件:

 

posted @ 2022-05-25 08:50  前端HL  阅读(492)  评论(0编辑  收藏  举报