通过一个案例,循序渐进的了解计算属性,这个案例通过不同的写法了解VUE的计算属性。
一、使用插值语法做一个示例
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>姓名案例-插值语法</title><script type="text/javascript" src="../js/vue.js"></script>
</head>
<body><div id="root">姓:<input type="text" v-model:value="firstname"><br/><br/>名:<input type="text" v-model:value="lastname"><br/><br/>全名:<span>{{firstname}}-{{lastname}}</span></div>
</body>
<script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:"#root",data:{firstname:"李",lastname:"国家",}})
</script>
</html>
二、 基于methods方法实现
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>姓名案例-methods实现</title><script type="text/javascript" src="../js/vue.js"></script></head>
<body><!-- 准备好一个容器 --><div id="root">姓:<input type="text" v-model:value="firstname"><br/><br/>名:<input type="text" v-model:value="lastname"><br/><br/>全名:<span>{{fullName()}}</span></div>
</body>
<script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:"#root",data:{firstname:"李",lastname:"国家",},methods:{//定义一个方法fullName(){return this.firstname + "-" + this.lastname}}})
</script>
</html>
三、 计算属性
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>姓名案例_计算属性实现</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',},computed:{//完整写法/* fullName:{get(){console.log('get被调用了')return this.firstName + '-' + this.lastName},set(value){console.log('set',value)const arr = value.split('-')this.firstName = arr[0]this.lastName = arr[1]}} *///简写fullName(){console.log('get被调用了')return this.firstName + '-' + this.lastName}}})</script>
</html>