Vue.js (a): By creating the first application Vue preliminary understanding of the data and methods Vue.js


The core Vue.js that allows the use of a simple declarative syntax template to render data into the DOM system. It has two major components: one is the view, one script.

First, the first application Vue

Let's create the first application Vue:

<!--视图-->
<div id="app">
    {{message}}
</div>
//脚本
<script type="text/javascript">
    var app = new Vue({
        el:'#app',
        data:{
            message:'Hello Vue!'
        }
    });
</script>

The following is a description of this code:

  • {{Message}} is the most common way text interpolation Vue.js
  • var app = new Vue () statement in the application object Vue.js
  • el: Element i.e., element attributes, div is selected by the mode selector
  • data: data attribute, which declares the view layer variables, which variables must be registered in the data and the initial value

Each application Vue is by creating a new instance of Vue Vue function begins with:

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

Although not completely follow the MVVM model, but the Vue's design also took its inspiration. So often we use vm (abbreviation of ViewModel) This variable represents the name Vue instance in the document.

Second, the data and methods

When a Vue instance is created, all properties it is added to the data object in response to the systems Vue. When the values ​​of these properties change, the view will produce a "response" that is updated to a new value matching. for example:

<!--视图-->
<div id="app">
    {{a}}
</div>
//脚本
<script type="text/javascript">
    var data = {a:1};
    var vm = new Vue({
        el:"#app",
        data:data
    });
</script>

The following is a description of this code:

  • Attribute data and variable data is not the same, with variable data represented in the form of objects

  • Divided into several cases to discuss this code:

    • How to modify the value of a can be achieved by effect responsive data.a = "text" in the back. When these data changes, the view will be re-rendered.

    • If the value b is modified by vm.a = "text", it may be responsive to achieve the effect, but data.a == vm.a

    • It is noteworthy that only when an instance is created in already exists in the data attribute is the type of response. If the response type of the desired effect, you must first declare the variable. If you know you'll need a property at a later date, but a start it is empty or does not exist, then you only need to set some initial values. such as:

      data: {
        newTodoText: '',
        visitCount: 0,
        hideCompletedTodos: false,
        todos: [],
        error: null
      }
      
  • If you use Object.freeze (), prevents modify an existing property, but also means that the system can no longer respond to track changes.

<div id="app">
  <p>{{ foo }}</p>
  <!-- 这里的 `foo` 不会更新! -->
  <button v-on:click="foo = 'baz'">Change it</button>
</div>
var obj = {
  foo: 'bar'
}

Object.freeze(obj)

new Vue({
  el: '#app',
  data: obj
})

In addition to data attributes, Vue also exposed some examples of useful methods and instance attributes. They have a $ prefix to distinguish the area of ​​the user-defined attribute. such as:

var data = { a: 1 }
var vm = new Vue({
  el: '#example',
  data: data
})

vm.$data === data 
vm.$el === document.getElementById('example') 

Third, the usual method of instance data and instance attributes

1, examples of the properties
Attributes description
vm.$data Acquiring property
vm. $ the Gets an instance of a mounted element
vm.$options Get custom options / properties / function
vm.$refs Get registered with the ref attribute of the DOM objects

Code examples:

<div>
			<h1>{{msg}}</h1>
			<h2 ref='hello'>Hello</h2>
			<h2 ref='vue'>Vue</h2>
</div>
<script>
		let vm = new Vue({
				el : 'div',
				data : {
					msg : 'sikiedu'
				},
				username : 'joey',
				password : '123',
				login(){
					console.log("login");
				}
			});
			
			/*$.data*/
  		    console.log(vm.$data.msg);
			console.log(vm.msg);
			
			/*$el*/
			console.log(vm.$el);
			vm.$el.style.color = 'red';
 
			/*$options*/
			console.log(vm.$options.username);
			console.log(vm.$options.password);
			vm.$options.login();
			
			/*$refs*/
			console.log(vm.$refs);
			vm.$refs.hello.style.backgroundColor = 'yellow';
			
	</script>
2. The method of instance data
method description
vm.$watch Observation data changes
vm.$delete Delete attribute values
vm.$set Set property values

Examples delete codes and set methods:

<div>
			Id:<span>{{user.id}}</span><br />
			用户名:<span>{{user.username}}</span><br />
			<button @click="changeUsername">changeUsername</button><br />
			<button @click="addId">addId</button><br />
			<button @click="delId">delId</button>
</div>
<script>
		let vm = new Vue({
				el : 'div',
				data : {
					user : {
						username : 'Joey'
					}
				},
				methods : {
					changeUsername(){
						this.user.username = 'sikiedu-Joey';
					},
					addId(){
						//this.$set(this.user, 'id', 1);  局部的
						//Vue.set(this.user, 'id', 1);   全局的
						
						if(this.user.id){
							this.user.id++;
						}else{
							Vue.set(this.user, 'id', 1);
						}
						console.log(this.user.id);
					},
					delId(){
						if(this.user.id){
							//this.$delete(this.user, 'id');
							Vue.delete(this.user, 'id');
						}
					}
				}
			});
			
	</script>

Method watch code examples:

<div>
			<input type="text" v-model="msg" /><br />
			msg : <span>{{msg}}</span><br />
			
			<input type="text" v-model="num" /><br />
			num : <span>{{num}}</span><br />
			
			<button οnclick="unWatch()">unWatch</button>
			
</div>
<script>
		let vm = new Vue({
				el : 'div',
				data : {
					msg : 'Joey',
					num : 1,
					user : {
						id : '01',
						username : 'sikiedu'
					}
				},
				watch : {
					num : function(newValue, oldValue){
						console.log("修改了num 旧值= " + oldValue + "   新值= " + newValue);
					}
				}
			});
			
			let unwatch = vm.$watch('msg', function(newValue, oldValue){
					console.log("修改了msg 旧值= " + oldValue + "   新值= " + newValue);
			});
			
			function unWatch(){
				unwatch();
				console.log("点击了unwatch按钮")
			}
			
</script>
Published 17 original articles · won praise 15 · views 883

Guess you like

Origin blog.csdn.net/abc701110/article/details/104876666