Vue学习—实例(二)实例方法

  1. vm.$mount:用法:如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。可以使用 vm.$mount() 手动地挂载一个未挂载的实例。如果没有提供 elementOrSelector 参数,模板将被渲染为文档之外的的元素,并且你必须使用原生 DOM API 把它插入文档中。这个方法返回实例自身,因而可以链式调用其它实例方法。
    < body>
    < h1>实例方法 </ h1>
    < div id= "app">
    {{message}}
    < div class= "text">{{message}}</ div>
    </ div>
    < script>
    var abc = Vue. extend({
    template: "<p>{{message}}</p>",
    data: function () {
    return {
    message: "Hello my Girl!"
    }
    }
    })
    new abc(). $mount( "#app"); //将abc挂载到app上
    </ script>
    </ body>

  2. vm.$destroy():完全销毁一个实例。清理它与其它实例的连接,解绑它的全部指令及事件监听器。这个方法会触发 beforeDestroy 和 destroyed 的钩子。在大多数场景中你不应该调用这个方法。最好使用 v-if 和 v-for 指令以数据驱动的方式控制子组件的生命周期。
    < p>
    < button onclick= "xiezai()">卸载</ button>
    </ p>
    < div id= "app">
    {{message}}
    < div class= "text">{{message}}</ div>
    </ div>

    < script>
    var abc = Vue. extend({
    template: "<p>{{message}}</p>",
    data: function () {
    return {
    message: "Hello my Girl!"
    }
    },
    destroyed: function () {
    console. log( "销毁之后");
    }
    })
    var vm = new abc(). $mount( "#app"); //将abc挂载到app上并且命名为vm
    function xiezai() {
    vm. $destroy();
    }
    </ script>
  3. vm.$forceUpdate(): 迫使 Vue 实例重新渲染。注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。
    < p>
    < button onclick= "update()">刷新</ button>
    </ p>
    < div id= "app">
    {{message}}
    </ div>
    < script>
    var abc = Vue. extend({
    template: "<p>{{message}}</p>",
    data: function () {
    return {
    message: "Hello my Girl!"
    }
    },
    updated: function () {
    console. log( "被更新之后");
    }
    })

    function update() {
    vm. $forceUpdate();
    }
    </ script>
  4. vm.$nextTick:将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 Vue.nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。
    < p>
    < button onclick= "xiugai()">修改</ button>
    </ p>
    < div id= "app">
    {{message}}
    </ div>
    < script>
    var abc = Vue. extend({
    template: "<p>{{message}}</p>",
    data: function () {
    return {
    message: "Hello my Girl!"
    }
    },
    destroyed: function () {
    console. log( "销毁之后");
    },
    updated: function () {
    console. log( "被更新之后");
    }
    });
    var vm = new abc(). $mount( "#app");
    function xiugai() {
    vm. $nextTick( function () {
    console. log( "更新完后被调用");
    });
    }

猜你喜欢

转载自blog.csdn.net/qq_41581499/article/details/79975858