App.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <template>
  2. <h2>ref 和 setup的基本使用</h2>
  3. <h3>{{ count }}</h3>
  4. <button @click="updateCount">按钮</button>
  5. </template>
  6. <script lang="ts">
  7. import { defineComponent,ref } from 'vue'
  8. export default defineComponent({
  9. //需求: 页面打开后就可以看到一个数据,点击按钮,数据可以发生变化
  10. //vue2也可以在vue3里面去写
  11. //vue2的写法
  12. // data(){
  13. // return{
  14. // count: 0
  15. // }
  16. // },
  17. // methods:{
  18. // updateCount(){
  19. // this.count++
  20. // }
  21. // }
  22. //vue3实现
  23. //setup是一个入口函数
  24. setup () {
  25. // let count = 0 //数据不是响应式数据 (响应式数据: 数据变化,页面也跟着发生变化)
  26. //ref函数 作用:就是定义一个响应式的数据 返回的是一个ref对象 对象中有一个value属性
  27. //如果需要对数据进行操作 需要使用ref对象 value属性的方式进行数据操作
  28. //html模板中是不需要使用 .value属性的
  29. //语法:const xxx = ref(initValue)
  30. //ts中操作数据 xxx.value
  31. const count = ref(0)
  32. function updateCount(){
  33. //报错的原因是因为count是一个ref对象 对象不能进行++操作
  34. // count++
  35. console.log(count)
  36. count.value ++
  37. }
  38. return {
  39. count,
  40. updateCount
  41. }
  42. }
  43. })
  44. </script>
  45. <style scoped>
  46. </style>