015、Vue3+TypeScript基础,使用watch监视ref定义的基本类型数据

01、App.vue代码如下:

<template>
  <div class="app">
    <h2>{{ title }}</h2>
    <!--    使用了ref来获取子组件的属性-->
    <Person/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue'
import {ref} from 'vue'

let title = ref('好好学习,天天向上')

</script>

<!--样式 scoped表示仅本单元有效-->
<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

02、Person.vue代码如下:

<template>
  <div class="person">
    <h1>情况一:监视【ref】定义的【基本类型】数据</h1>
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点我sum+1</button>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import {ref, watch} from 'vue'

let sum = ref(0)

// 按钮点击事件
function changeSum() {
  sum.value += 1;
}

// 监视sum
watch(sum, (newVal, oldVal) => {
  console.log('sum变化了,由', oldVal, '变为:', newVal)
})
</script>
<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }
}
</style>

03、效果如下:

 

posted @ 2024-08-18 00:07  像一棵海草海草海草  阅读(2)  评论(0编辑  收藏  举报