123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <template>
- <h2>ref 和 setup的基本使用</h2>
- <h3>{{ count }}</h3>
- <button @click="updateCount">按钮</button>
- </template>
- <script lang="ts">
- import { defineComponent,ref } from 'vue'
- export default defineComponent({
- //需求: 页面打开后就可以看到一个数据,点击按钮,数据可以发生变化
- //vue2也可以在vue3里面去写
- //vue2的写法
- // data(){
- // return{
- // count: 0
- // }
- // },
- // methods:{
- // updateCount(){
- // this.count++
- // }
- // }
- //vue3实现
- //setup是一个入口函数
- setup () {
- // let count = 0 //数据不是响应式数据 (响应式数据: 数据变化,页面也跟着发生变化)
-
- //ref函数 作用:就是定义一个响应式的数据 返回的是一个ref对象 对象中有一个value属性
- //如果需要对数据进行操作 需要使用ref对象 value属性的方式进行数据操作
- //html模板中是不需要使用 .value属性的
- //语法:const xxx = ref(initValue)
- //ts中操作数据 xxx.value
- const count = ref(0)
- function updateCount(){
- //报错的原因是因为count是一个ref对象 对象不能进行++操作
- // count++
- console.log(count)
- count.value ++
- }
- return {
- count,
- updateCount
- }
- }
- })
- </script>
- <style scoped>
- </style>
|