1. 程式人生 > >vue小細節

vue小細節

模塊化 clas data function doc 實例名 title methods sel

1.vue.js裏的vm:

實例名稱~vm ~他是new出來的,

var vm=new Vue({})

 var app =new Vue({})

官方api用的vm,只是一個實例 2.vm.$el解讀:
var vm = new Vue({
el: ‘#app‘, router, template: ‘
<App/>‘, components: {App} }); console.log(vm.$el)

這裏,只能在入口文件中獲取vm.$el,並不能在其他文件獲取

通過 Vue 命令行使用 webpack 項目模板生成的項目,webpack 打包的基礎是模塊化,模塊是一個個封閉的上下文,不但入口文件中的私有變量不能被其他文件獲取,

所有文件中的私有變量都不能在其他文件中獲取。

只有通過 export 導出的值才可以在其他模塊中訪問,因此如果需要在其他模塊中使用 vm,你需要 export vm

$els類似於document.querySelector(‘.class‘)的功能,可以拿到指定的dom元素。

this.$el等於vm.$el

3.$mount()手動掛載

當Vue實例沒有el屬性時,則該實例尚沒有掛載到某個dom中;

假如需要延遲掛載,可以在之後手動調用vm.$mount()方法來掛載。例如:

<div id="app">
    {{a}}
</div>
<button 
onclick="test()">掛載</button> <script> var obj = {a: 1} var vm = new Vue({ data: obj }) function test() { vm.$mount("#app"); }

初始,顯示的是{{a}}

當點擊按鈕後,變成了1

4.vue生命周期:

技術分享圖片

運行結果如下:

技術分享圖片

代碼如下:

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"
> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id=app> {{a}} <br> <button v-on:click="greet">change</button> </div> <script> var myVue = new Vue({ el: "#app", data: { a: "hava data" }, methods:{ greet:function(){ this.a="changed data" } }, beforeCreate: function() { console.log("創建前") console.log(this.a) console.log(this.$el) }, created: function() { console.log("創建之後"); console.log(this.a+"........") console.log(this.$el) }, beforeMount: function() { console.log("mount之前") console.log(this.a+"........") console.log(this.$el) }, mounted: function() { console.log("mount之後") console.log(this.a+"........") console.log(this.$el) }, beforeUpdate: function() { console.log("更新前"); console.log(this.a+"........") console.log(this.$el) }, updated: function() { console.log("更新完成"); console.log(this.a+"........") console.log(this.$el) }, beforeDestroy: function() { console.log("銷毀前"); console.log(this.a) console.log(this.$el) console.log(this.$el) }, destroyed: function() { console.log("已銷毀"); console.log(this.a) console.log(this.$el) } }); </script> </body> </html>

vue小細節