Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue.js Getting Started

Vue.js Getting Started

Every Vue application needs to be created by instantiating Vue.

The syntax format is as follows:

var vm = new Vue({

  // 选项

})

Next let's look at what is needed in the Vue constructor through an example:

Example

<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: "Runoob Tutorial", url: "www.runoob.com", alexa: "10000" }, methods: { details: function() { return this.site + " - Learning is not just about technology, but also about dreams!"; } } })

script

Try it »

Click the "Try it" button to view the online example

You can see there is an el parameter in the Vue constructor; it is the id of a DOM element. In the example above the id is vue_det, in the div element:

This means all our subsequent changes are within the specified div; anything outside the div is unaffected.

Next let's see how to define the data object.

data Used to define properties; the instance has three properties: site, url, alexa.

methods is used to define functions, which can return a value via return.

{{ }} is used to output object properties and function return values.

    

site : {{site}}

    

url : {{url}}

    

{{details()}}

When a Vue instance is created, it adds all the properties found in its data object to Vue's reactivity system. When the values of these properties change, the html view will change accordingly.

Example

<div id="vue_det">
<h1>

site : {{site}}

h1

<

h1

url : {{url}}

h1

<

h1

Alexa : {{alexa}}

h1

div

<script type="text/javascript">

// Our data object var data = { site: "Runoob Tutorial", url: "www.runoob.com", alexa: 10000} var vm = new Vue({ el: '#vue_det', data: data }) // They reference the same object! document.write(vm.site === data.site) // true document.write("

<

br

") // Setting a property also affects the original data vm.site = "Runoob" document.write(data.site + "

<

br

") // Runoob // ... and vice versa data.alexa = 1234 document.write(vm.alexa) // 1234

script

Try it »

Besides data properties, Vue instances also expose some useful instance properties and methods. They are prefixed with $ to distinguish them from user-defined properties. For example:

Example

<div id="vue_det">
<h1>

site : {{site}}

h1

<

h1

url : {{url}}

h1

<

h1

Alexa : {{alexa}}

h1

div

<script type="text/javascript">

// Our data object var data = { site: "Runoob Tutorial", url: "www.runoob.com", alexa: 10000} var vm = new Vue({ el: '#vue_det', data: data }) document.write(vm.$data === data) // true document.write("

<

br

") document.write(vm.$el === document.getElementById('vue_det')) // true

script

Try it »