每个Vue应用都需要通过实例化Vue来实现
var vm = new Vue({
// 选项
})
具体案例
<div id="vue_det">
<h1>site : {{site}}</h1>
<h1>url : {{url}}</h1>
<h1>{{details()}}</h1>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#vue_det',
data: {
site: "菜鸟教程",
url: "www.runoob.com",
alexa: "10000"
},
methods: {
details: function() {
return this.site + " - 学的不仅是技术,更是梦想!";
}
}
})
</script>
可以看到Vue构造器中有一个el参数,它是DOM元素中的id。在上面案例中id为vue_det,在div元素中
<div id = "vue_det"></div>
如何定义数据对象
<div id="vue_det">
<h1>site : {{site}}</h1>
<h1>url : {{url}}</h1>
<h1>{{details()}}</h1>
</div>
当一个Vue实例被创建时,它向Vue的响应式系统中加入了其data对象中能找到的所有的属性。当这些属性的值发生改变时,html视图将也会发生相应的变化
<div id="vue_det">
<h1>site : {{site}}</h1>
<h1>url : {{url}}</h1>
<h1>Alexa : {{alexa}}</h1>
</div>
<script type="text/javascript">
// 我们的数据对象
var data = { site: "菜鸟教程", url: "www.runoob.com", alexa: 10000}
var vm = new Vue({
el: '#vue_det',
data: data
})
// 它们引用相同的对象!
document.write(vm.site === data.site) // true
document.write("<br>")
// 设置属性也会影响到原始数据
vm.site = "Runoob"
document.write(data.site + "<br>") // Runoob
// ……反之亦然
data.alexa = 1234
document.write(vm.alexa) // 1234
</script>
除了数据属性,Vue实例还提供了一些有用的实例属性与方法。它们有前缀$,以便与用户定义的属性区分开
document.write(vm.$data === data) // true
document.write("<br>")
document.write(vm.$el === document.getElementById('vue_det')) // true