Blogger Information
Blog 250
fans 3
comment 0
visits 322830
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Vue自学:为什么组件data必须是个函数
梁凯达的博客
Original
1548 people have browsed it
  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>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post