Vue2起步

2/18/2020

# 实例化Vue

每个 Vue 应用都是通过实例化 Vue 来实现。

var vm = new Vue({
  // 选项
})
1
2
3

当我们在浏览器控制台看到Vue的警告时,即表示实例创建成功。

vue实例创建

接下来看Vue构建时一般需要的参数。

<div id="app">
    <h1>name : {{name}}</h1>
    <h1>age : {{age}}</h1>
    <h1>{{printMsg()}}</h1>
</div>
<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            name: "snake8859",
            age: 22
        },
        methods: {
            printMsg: function() {
                return  this.name+':'+this.age;
            }
        }
    })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  • el

    el是element缩写,它的值是DOM元素的id,当指定对应DOM元素的id后,表示DOM元素节点下所有内容vue接手管理。

    el有两种写法:

    1. 创建Vue的时候指定元素
    2. 先创建Vue实例,然后通过vm.$mount('#app')
  • data

    data用于定义属性,它的值是键值对形式,如实例中有两个属性name和age。可以结合插值表达式{{}},将属性值输出。

    data有两种写法:

    1. 对象式:data: {}
    2. 函数式:data(){ return { } }
  • methods

    method用于定义函数,可以将事件绑定函数,工具函数定义在其中,以便使用。

更多具体的选项内容,可参考传送门 (opens new window)

# 生命周期

Vue实例创建时,需要经历一系列过程,在这个过程中也会运行某些特定的函数,将这些函数称之为生命周期钩子函数。这给我们在不同阶段可以添加相应的代码,完成某些初始化任务等。

生命周期.png

<body>
		<div id="app">
			{{message}}
		</div>
</body>
	<script>
		var vm = new Vue({
			el: "#app",
			data: {
				message: 'hello world'
			},
			beforeCreate: function() {
				console.log(this);
				showData('创建vue实例前', this);
			},
			created: function() {
				showData('创建vue实例后', this);
			},
			beforeMount: function() {
				showData('挂载到dom前', this);
			},
			mounted: function() {
				showData('挂载到dom后', this);
			},
			beforeUpdate: function() {
				showData('数据变化更新前', this);
			},
			updated: function() {
				showData('数据变化更新后', this);
			},
			beforeDestroy: function() {
				vm.test = "3333";
				showData('vue实例销毁前', this);
			},
			destroyed: function() {
				showData('vue实例销毁后', this);
			}
		});

		function realDom() {
			console.log('真实dom结构:' + document.getElementById('app').innerHTML);
		}

		function showData(process, obj) {
			console.log(process);
			console.log('data 数据:' + obj.message)
			console.log('挂载的对象:')
			console.log(obj.$el)
			realDom();
			console.log('------------------')
			console.log('------------------')
		}
		//vm.message = "good...";
		vm.$destroy(); 
	</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

更多具体内容,可参考传送门 (opens new window)

Last Updated: 8/23/2023, 2:39:40 PM