登录  /  注册
博主信息
博文 250
粉丝 3
评论 0
访问量 370448
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
Vue自学:为什么组件data必须是个函数
梁凯达的博客
原创
2187人浏览过
  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
  8. <title>Vue自学:为什么组件data必须是个函数</title>
  9. </head>
  10. <body>
  11. <div id="app">
  12. <cpn></cpn>
  13. <cpn></cpn>
  14. <cpn></cpn>
  15. </div>
  16. </body>
  17. <!-- 所使用的template模板标签内,必须再嵌套一层div,否则会显示不全 -->
  18. <template id="cpn">
  19. <div>
  20. <h1>当前计数值为:{{message}}</h1>
  21. <button type="button" v-on:click="add">+</button>
  22. <button type="button" v-on:click="reduce">-</button>
  23. </div>
  24. </template>
  25. <script type="text/javascript">
  26. //子组件
  27. Vue.component('cpn',{
  28. template:'#cpn',
  29. //data必须是个函数,原因是函数在复用时可以做到唯一性
  30. //当data不是一个函数的时候,组件标签在复用的时候,会使得数据重复错乱
  31. data(){
  32. return {
  33. message:0,
  34. }
  35. },
  36. methods:{
  37. add(){
  38. this.message++
  39. },
  40. reduce(){
  41. this.message--
  42. }
  43. }
  44. })
  45. //父组件
  46. const app = new Vue({
  47. el:'#app',
  48. data:{
  49. },
  50. methods:{
  51. }
  52. })
  53. //为什么data需要是一个函数
  54. //函数内部本身是一个独立的数据栈
  55. // function test(x,y){
  56. // let q = x;
  57. // let w = y;
  58. // console.log(q,w);
  59. // }
  60. // let obj1 = test(1,2)
  61. // let obj2 = test(3,4)
  62. // let obj3 = test(5,6)
  63. // console.log(obj1,obj2,obj3)
  64. //当函数内部引用的东西是外部常量时,当外部常量事先被更改后
  65. //再次打印函数,整个变量的值都会被改变
  66. const obj = {
  67. name:'wang xiao er',
  68. age:'18',
  69. }
  70. function abc(){
  71. return obj
  72. }
  73. let obj1 = abc()
  74. let obj2 = abc()
  75. let obj3 = abc()
  76. obj1.name = 'koby'
  77. console.log(obj1,obj2,obj3)
  78. </script>
  79. </html>
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学