Bootstrap

Vue 实例

一、页面效果图

在这里插入图片描述

二、代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="../vue.js" type="text/javascript"></script>
		<title>vue 实例</title>
	</head>
	<body>

		<div id="vm1">
			{{message}} --- {{a}}
		</div>

		<div id="freeze">
			<p>{{foo}}</p>
			<!-- 这里的 `foo` 不会更新! -->
			<button v-on:click="foo = barz">Change it </button>
		</div>

		<script>
			//数据对象
			var data = {
				message: 'vue 实例',
				a: 1
			}
			//每个 Vue 应用都是通过用 Vue 函数创建一个新的 Vue 实例开始的:
			//该对象被加入到一个Vue实例
			var vm1 = new Vue({
				el: '#vm1',
				data: data
			})

			// 获得这个实例上的 property
			// 返回源数据中对应的字段
			vm1.a == data.a // true
			// 设置 property 也会影响到原始数据
			vm1.a = 2
			data.a // = 2

			//反之亦然
			data.a = 3
			vm1.a // = 3

			// Object.freeze(),这会阻止修改现有的 property,也意味着响应系统无法再追踪变化
			var obj = {
				foo: 'bar'
			}

			Object.freeze(obj)

			var freeze = new Vue({
				el: '#freeze',
				data: obj
			})

			//Vue 实例还暴露了一些有用的实例 property 与方法。它们都有前缀 $,以便与用户定义的 property 区分开来。例如:

			vm1.$data == data
			vm1.$el === document.getElementById('vm1') // true
			console.log(vm1.$el === document.getElementById('vm1')) // true


			var watchFuntion = function(newValue, oldValue) {
				// console.log('newValue = ' + newValue + '  oldValue = ' + oldValue)
				console.log('newValue = ', newValue, '  oldValue = ', oldValue)
			}


			// $watch 是一个实例方法,在变量改变前声明
			// 这个回调将在 `vm.a` 改变后调用
			vm1.$watch('a', watchFuntion)
			vm1.a = 4
		</script>
	</body>
</html>

三、LearnVue 源码

点击查看LearnVue 源码

四、推荐阅读

Vue教程

;