Vue2 混入mixins

效果:

native message

您的代办事项有:3 件 

  控制台输出:

created in overrall

created in aaa

created in native

mounted in overrall

mounted in aaa

mounted in native

  点击+按钮,控制台输出:

addItem in native

可见,混入的生命周期钩子事件执行顺序是:先全局混入,再局部混入,最后构造器。

混入的data和methods将被构造器覆盖。


代码:

<h1>Mixins-混入属性和方法等到构造器内部</h1>
<div id="app2">
    {{ message }}
    <p>您的代办事项有:{{ count }} 件 <button @click="addItem"> + </button></p>
</div>
<script>
    //全局混入 用于权限校验或调研用户习惯 慎用
    Vue.mixin({
        data:function () {
          return {
              message:"overrall message"
          }
        },
        created:function () {
            console.log("created in overrall");
        },
        mounted:function () {
            console.log("mounted in overrall");
        }
    });

    //局部混入 常用于开发阶段的测试
    var aaa={
        data:{
            message:"aaa message"
        },
        methods:{
            addItem:function () {
                console.log("addItem in aaa");
            }
        },
        created:function () {
            console.log("created in aaa");
        },
        mounted:function () {
            console.log("mounted in aaa");
        }
    };

    var vm = new Vue({
        el:"#app2",
        data:{
            message:"native message",
            count:3
        },
        methods:{
            addItem:function () {
                console.log("addItem in native");
            }
        },
        created:function () {
            console.log("created in native");
        },
        mounted:function () {
            console.log("mounted in native");
        },
        mixins:[aaa]
    });
</script>

阅读更多
个人分类: vue
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Vue2 混入mixins

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭