對vue計算屬性computed的setter與getter的理解

大家都知道computed簡單的使用方法,這兒只分享一下setter和getter用法:

setter:設置值時觸發。

getter:獲取值時觸發,與setter是沒有必然聯繫的。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<button @click="setter">設置</button>
			<p>原始數據:</p>
			<p>{{fullName}}</p>
		</div>
	</body>
	<script type="text/javascript">
		let vm = new Vue({
		  // 選項
		  el: '#app',
		  data:{
		  	provice:'Guangdong',
		  	city:'guangzhou'
		  },
		  methods:{
		  	setter:function(){
		  		this.provice='Taiwan'
		  		this.city='taipei'
		  	}
		  },
		  computed: {
			  fullName: {
			    // getter
			    get: function () {
			      return this.provice + ' ' + this.city
			    },
			    // setter
			    set: function (newValue) {
		    	  console.log(newValue);
			      let names = newValue.split(' ')
			      this.provice = names[0]
			      this.city = names[names.length - 1]
			    }
			  }
			}
		})
	</script>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章