02.计算属性:

计算属性:

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://unpkg.com/vue/dist/vue.js"></script>
	</head>
	<body>
		<div id="vue1">
			<h3>计算属性</h3>
			{{name.substring(0,1).toUpperCase()+name.substring(1)}}
			<h3>计算属性 VS methods</h3>
			<p>我是计算属性{{changeword}}</p>
			<p>我是计算属性{{changeword}}</p>
			<p>我是普通方法{{changewordMethod()}}</p>
			<p>我是普通方法{{changewordMethod()}}</p>
			
			<h3>计算属性 VS watch</h3>
			<p>单价:<input type="text" v-model="price"/></p>
			{{price}}
			<p>数量:<input type="text" v-model="number"/></p>
			{{number}}
			<p>总额:<span>{{sum}}</span></p>
			<p>计算属性总额:<span>{{computedsum}}</span></p>
			
			<h3>计算属性setter</h3>
			<p>{{getData}}</p>
			
		</div>
		<script type="text/javascript"> 
			var vm = new Vue({ 
				el: "#vue1",
				data: {
					"name": "xiaoming",
					"price":100,
					"number":0,
					"sum":0
				},
				#计算属性
				computed:{
					changeword:function(){
						console.log("计算属性");
						return this.name.substring(0,1).toUpperCase()+this.name.substring(1)
					},
					computedsum:function(){
						return this.number*this.price
					},
					getData:{
						get:function(){
							return "获取";
						},
						set:function(val){
							console.log(val);
						},
					}
					
					
				},
				#方法
				methods:{
					changewordMethod:function(){
						console.log("普通方法");
						return this.name.substring(0,1).toUpperCase()+this.name.substring(1)
					}
				},
				#watch
				watch:{
					price:function(val){
						console.log(val);
						this.sum=val*this.number
					},
					number:function(val){
						this.sum=val*this.price
					}
				}
				
			})
		</script>
	</body>
</html>

计算属性:

为了实现单词首字母大写,可以在模板语法中直接写,但是这样写模板中太多代码,太重,太难维护。所以有了计算属性。

计算属性和方法对比:

计算属性就是一个属性,但在写的时候用function。

方法和计算属性达到的想过看起来是一样的。

但是如果在一个程序中调用两次方法,那么方法methods里的会调用两次。

而计算属性只会调用computed里的一次,计算属性会缓存,第二次不会调用computed里的。

计算属性和watch对比:

首先在用watch是会先用到一个指令v-model,可以双向监听。

在这个例子中watch达到的效果是:当price或者number某一个发生改变,总额里的也会发生改变。

但是代码相对计算属性比较繁琐。

计算属性setter:

可以看代码运行了解下,实际用途不大。

猜你喜欢

转载自blog.csdn.net/weixin_42903932/article/details/86664842