VueJS教程
+ -

VueJS 计算属性(Computed)

2019-09-09 1 0

我们已经看到了Vue实例和组件的方法。计算属性(Computed Properties)类似于方法,但与方法相比有一些区别,我们将在本章中讨论。

让我们通过一个例子来了解计算属性。

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "computed_props">
         FirstName : <input type = "text" v-model = "firstname" /> <br/><br/>
         LastName : <input type = "text" v-model = "lastname"/> <br/><br/>
         <h1>My name is {{firstname}} {{lastname}}</h1>
         <h1>Using computed method : {{getfullname}}</h1>
      </div>
      <script type = "text/javascript" src = "js/vue_computedprops.js"></script>
   </body>
</html>

vue_computeprops.js

 var vm = new Vue({
   el: '#computed_props',
   data: {
      firstname :"",
      lastname :"",
      birthyear : ""
   },
   computed :{
      getfullname : function(){
         return this.firstname +" "+ this.lastname;
      }
   }
})

我 们正在调用计算方法getfullname,该方法返回输入的名字和姓氏。

  computed :{
   getfullname : function(){
      return this.firstname +" "+ this.lastname;
   }
}

当我们在文本框中键入内容时,如果更改属性firstname或lastname,则函数会返回相同的内容。

1604672218863

使用以下示例,让我们了解方法(method)和计算属性(computed)之间的区别。

< html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "computed_props">
         <h1 style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h1>
         <h1>Random No from method: {{getrandomno1()}}</h1>
         <h1>Random No from method : {{getrandomno1()}}</h1>
         <h1  style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h1>
         <h1  style = "background-color:gray;">Random No from computed property: {{getrandomno}}</h1>
         <h1  style = "background-color:gray;">Random No from computed
            property: {{getrandomno}}</h1>
         <h1>Random No from method: {{getrandomno1()}}</h1>
         <h1>Random No from method: {{getrandomno1()}}</h1>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#computed_props',
            data: {
               name : "helloworld"
            },
            methods: {
               getrandomno1 : function() {
                  return Math.random();
               }
            },
            computed :{
               getrandomno : function(){
                  return Math.random();
               }
            }
         });
      </script>
   </body>
</html>

在上面的代码中,我们创建了一个名为 getrandomno1 的方法和一个带有函数 getrandomno 的计算属性,两者都使用Math.random()返回随机数。

它显示在浏览器中,如下所示。多次调用方法和计算属性以显示差异。

1604672228706

如果我们看一下上面的值,我们将看到从计算属性返回的随机数保持不变,而与调用它的次数无关。这意味着每次调用时,所有的最后一个值都会更新。对于方法来说,它是一个函数,因此,每次调用它都会返回一个不同的值。

get/set 计算属性

在本节中,我们将通过一个示例来了解计算属性中的get/sest函数。

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "computed_props">
         <input type = "text" v-model = "fullname" />
         <h1>{{firstName}}</h1>
         <h1>{{lastName}}</h1>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#computed_props',
            data: {
               firstName : "Terry",
               lastName : "Ben"
            },
            methods: {
            },
            computed :{
               fullname : {
                  get : function() {
                     return this.firstName+" "+this.lastName;
                  }
               }
            }
         });
      </script>
   </body>
</html>

我们定义了一个绑定到 全 名的输入框,该输入框是一个计算属性。它返回一个名为 get 的函数,该函数给出全名,即名字和姓氏。另外,我们将名字和姓氏显示为-

< h1>{{firstName}}</h1>
<h1>{{lastName}}</h1>

让我们在浏览器中检查一下。

1604672242798

现在,如果我们在文本框中更改名称,我们将看到以下屏幕快照中显示的名称中未反映出相同的名称。

1604672248711

让我们在全名计算属性中添加setter函数。

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "computed_props">
         <input type = "text" v-model = "fullname" />
         <h1>{{firstName}}</h1>
         <h1>{{lastName}}</h1>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#computed_props',
            data: {
               firstName : "Terry",
               lastName : "Ben"
            },
            methods: {
            },
            computed :{
               fullname : {
                  get : function() {
                     return this.firstName+" "+this.lastName;
                  },
                  set : function(name) {
                     var fname = name.split(" ");
                     this.firstName = fname[0];
                     this.lastName = fname[1]
                  }
               }
            }
         });
      </script>
   </body>
</html>

我们在全名计算属性中添加了set函数。

computed :{
   fullname : {
      get : function() {
         return this.firstName+" "+this.lastName;
      },
      set : function(name) {
         var fname = name.split(" ");
         this.firstName = fname[0];
         this.lastName = fname[1]
      }
   }
}

现在,当我们运行代码并编辑文本框时,相同的内容将显示在浏览器中。如果编辑了任何内容,get函数将返回名字和姓氏,而set函数将对其进行更新。

1604672254173

0 篇笔记 写笔记

VueJS 计算属性(Computed)
我们已经看到了Vue实例和组件的方法。计算属性(Computed Properties)类似于方法,但与方法相比有一些区别,我们将在本章中讨论。让我们通过一个例子来了解计算属性。 VueJs Instance&...... </div> </div> </div> </main> <div class="column right-column" style="border:0px;"> <div class="card middle"> <div class="card-header "> <a class="collapsed card-link" data-toggle="collapse" href="#">技术专栏</a> </div> <div class="collapse show"> <li class="list-inline list-group-item list-group-item-action"><a title=".NET Core教程" href="/dotnet-core/index.html">.NET Core教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="A/B测试教程" href="/ab-testing/index.html">A/B测试教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="ADO.Net教程" href="/ado-net/index.html">ADO.Net教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="AIML教程" href="/aiml/index.html">AIML教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Ajax教程" href="/ajax/index.html">Ajax教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="ARP教程" href="/arp/index.html">ARP教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="BIOS编程教程" href="/bios/index.html">BIOS编程教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Bochs模拟器教程" href="/bochs/index.html">Bochs模拟器教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C#教程" href="/csharp/index.html">C#教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C++11教程" href="/cpp11/index.html">C++11教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C++教程" href="/cpp/index.html">C++教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C++标准库" href="/cppstdlib/index.html">C++标准库</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C/C++技巧" href="/ccpp-skill/index.html">C/C++技巧</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="CEF浏览器" href="/cef/index.html">CEF浏览器</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="CENTOS7教程" href="/centos7/index.html">CENTOS7教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="C语言教程" href="/c/index.html">C语言教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="dedecms5.7原代码分析" href="/dedecms/index.html">dedecms5.7原代码分析</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Docker教程" href="/docker/index.html">Docker教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="gcc命令选项教程" href="/gcc/index.html">gcc命令选项教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Go语言教程" href="/go/index.html">Go语言教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="H264学习资料" href="/h264/index.html">H264学习资料</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Java教程" href="/java/index.html">Java教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="jQuery教程" href="/jquery/index.html">jQuery教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="JSON教程" href="/json/index.html">JSON教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Libuv教程" href="/libuv/index.html">Libuv教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Linux" href="/linux/index.html">Linux</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Linux命令大全" href="/linuxcmd/index.html">Linux命令大全</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Linux驱动教程" href="/linuxdriver/index.html">Linux驱动教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Lua教程" href="/lua/index.html">Lua教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="MakeFile教程" href="/makefile/index.html">MakeFile教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Memcached教程" href="/memcached/index.html">Memcached教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="MongoDB教程" href="/mongodb/index.html">MongoDB教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="MySQL数据库" href="/mysql/index.html">MySQL数据库</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Nasm教程" href="/nasm/index.html">Nasm教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Nginx服务器" href="/nginx/index.html">Nginx服务器</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="ObjectiveC教程" href="/objectc/index.html">ObjectiveC教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="OsgEarth教程" href="/osgearth/index.html">OsgEarth教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Perl" href="/perl/index.html">Perl</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="PHP教程" href="/php/index.html">PHP教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="ProtcolBuffer教程" href="/protcolbuffer/index.html">ProtcolBuffer教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Python3教程" href="/python3/index.html">Python3教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="QT学习笔记" href="/qt/index.html">QT学习笔记</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Redis教程" href="/redis/index.html">Redis教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Ruby教程" href="/ruby/index.html">Ruby教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="SQLite" href="/sqlite/index.html">SQLite</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="SQL教程" href="/sql/index.html">SQL教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="UNIX/Linux教程" href="/unix/index.html">UNIX/Linux教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="VBScript教程" href="/vbscript/index.html">VBScript教程</a></li> <li class="list-inline list-group-item list-group-item-action active font-weight-bold" ><a style="color:#fff;" title="VueJS教程" href="/vuejs/index.html">VueJS教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="Windows运维大全" href="/windows/index.html">Windows运维大全</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="XPath教程" href="/xpath/index.html">XPath教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="关于本站" href="/about/index.html">关于本站</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="批处理教程" href="/bat/index.html">批处理教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="技术笔记" href="/blog/index.html">技术笔记</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="正则表达式教程" href="/regexp/index.html">正则表达式教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="设计模式教程" href="/designpattern/index.html">设计模式教程</a></li> <li class="list-inline list-group-item list-group-item-action"><a title="高质量 C++/C 编程指南" href="/highcpp/index.html">高质量 C++/C 编程指南</a></li> </div> </div> </div> </div> <footer> <div class="maincontent text-center"> <a href="/about/about.html">关于我们</a> <a href="/about/disclaimer.html">免责声明</a> <a href="/about/connect.html">侵删联系</a> <a href="/sitemap/sitemap.xml">网站地图</a> <br>Copyright © 2021 <a href="http://www.bytekits.com">字节流 QQ群:952873936</a> <a class="d-sm-inline d-none" href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow">陕ICP备19020272号-1</a> </div> </footer> <script src="/res/jquery2.1.1/jquery-2.1.1.min.js"></script> <script src="/res/bootstrap4.1.0/bootstrap.min.js"></script> <script src="/res/bootstrap-toggle/bootstrap-toggle.js"></script> <script src="/res/prettyPrint/prettify.js"></script> <script src="/res/js/main.js"></script> <script src="/res/feedback/js/jquery.feedback.js"></script> <script src="/res/feedback/js/feedback.js"></script> <script src="/res/share/jquery.share.min.js"></script> <script src="/res/js/third-www.js"></script> <script type="text/javascript" src="/res/simditor-2.3.19/scripts/module.js"></script> <script type="text/javascript" src="/res/simditor-2.3.19/scripts/hotkeys.js"></script> <script type="text/javascript" src="/res/simditor-2.3.19/scripts/uploader.js"></script> <script type="text/javascript" src="/res/simditor-2.3.19/scripts/simditor.js"></script> <script> $(function() { $("#share_code").click(function(){ $("#commentform").toggle(); }); $("#ShowNote").click(function() { $("#NoteList").toggle(); if($("#ShowNote i").hasClass("fa-minus-square")) { $("#ShowNote i").removeClass("fa-minus-square"); $("#ShowNote i").addClass("fa-square"); } else { $("#ShowNote i").removeClass("fa-square"); $("#ShowNote i").addClass("fa-minus-square"); } }); if("undefined" != typeof Simditor) { toolbar = ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment']; mobileToolbar = ["bold", "underline", "strikethrough", "color", "ul", "ol"]; //if (mobilecheck()) { // toolbar = mobileToolbar; //} var editor = new Simditor({ textarea: $('#editor'), placeholder: '写内容...', upload:false, defaultImage: '/res/img/comm/top-logo.png', codeLanguages: '', toolbar: toolbar }); editor.on('selectionchanged', function() { $(".code-popover").hide(); }); } var commentform=$('#commentform'); commentform.submit(function(e){ e.preventDefault(); var NoteContent = editor.getValue(); if(NoteContent.length<20) { alert("内容太短"); return; } var request = JSON.stringify({ArticleDetailId:ArticleDetailId,ArticleCommentContent:NoteContent}); $.post("/my/http.php", { action:"MakeArticleComment", request:request }, function(data,status) { console.log(data); json= JSON.parse(data); if(json.status ==0) { var NoetList=$("NoteList"); NoteContent = NoteContent.replace(/<pre><code>/g,"<pre>"); NoteContent = NoteContent.replace(/<\/code><\/pre>/g,"</pre>"); NoteContent +="<a href=\"/"+json.UserAccount+"\"/>"+json.UserNickName+"</a>"; NoteContent +=" "+json.CreateTime; console.log(NoteContent); var n=document.createElement("div"); n.innerHTML=NoteContent; NoteList.append(n); editor.setValue(''); } else { alert(json.info); } }); }); }); </script> <div id="container_drag" style="display:none;"></div> <script> var ArticleDetailId=590; </script> <div class="fixbottom" style="overflow:hidden;" > <button type="button" class="btn btn-secondary" style="font-weight:normal" id="feedback">技术提问/意见反馈</button> </div> <div class="fixed-btn"> <a class="go-top" href="javascript:void(0)" title="返回顶部" style="display: inline-block;"> <i class="fa fa-angle-up"></i></a> <a class="writer" href="javascript:void(0)" title="标记/收藏"><i class="fa fa-star-o" id="BookMark2" aria-hidden="true"></i></a> <a class="qrcode" href="javascript:void(0)" title="关注我们"><i class="fa fa-qrcode"></i></a> <a class="dashang" href="javascript:void(0)" onclick="dashangToggle()" title="打赏,支持一下"><i class="fa fa-heart-o"></i></a> <div id="bottom-qrcode" style="display:none;"> <h6>加入QQ群</h6> <div class="panel-body"><img alt="微信关注" src="/res/img/comm//qq-qun.png"></div> </div> </div> <div class="hide_box"></div> <div class="shang_box"> <a class="shang_close" href="javascript:void(0)" onclick="dashangToggle()" title="关闭"><img src="/res/img/dashang/close.jpg" alt="取消" /></a> <div class="shang_tit">感谢您的支持,我会继续努力的!</div> <div class="shang_payimg"><img src="/res/img/dashang/alipay-img.jpg" alt="扫码支持" title="扫一扫" /></div> <div class="pay_explain">扫码打赏,你说多少就多少</div> <div class="shang_payselect"> <div class="pay_item checked" data-id="alipay"> <span class="radiobox"></span> <span class="pay_logo"><img src="/res/img/dashang/alipay-logo.jpg" alt="支付宝" /></span> </div> <div class="pay_item" data-id="wechat"> <span class="radiobox"></span> <span class="pay_logo"><img src="/res/img/dashang/wechatpay-logo.jpg" alt="微信" /></span> </div> </div> <div class="shang_info"> <p>打开<span id="shang_pay_txt">支付宝</span>扫一扫,即可进行扫码打赏哦</p> <p>您的支持,是我们前进的动力!</p> </div> </div> </script> </body> </html>