Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3使用watch

作者:—上花′Ing   发布日期:2025-05-24   浏览:106

// 使用 Vue 3 的 watch 监听数据变化

<template>
  <div>
    <input v-model="message" placeholder="edit me">
    <p>Message is: {{ message }}</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue';

export default {
  setup() {
    // 定义一个响应式变量
    const message = ref('');

    // 使用 watch 监听 message 的变化
    watch(message, (newValue, oldValue) => {
      console.log('message changed from', oldValue, 'to', newValue);
    });

    return {
      message
    };
  }
};
</script>

<style scoped>
/* 样式部分可以根据需要添加 */
</style>

解释说明:

  1. 定义响应式变量:使用 ref 创建了一个名为 message 的响应式变量,并将其初始值设为空字符串。
  2. 监听变化:使用 watch 函数监听 message 的变化。当 message 发生变化时,会触发回调函数,该回调函数接收两个参数:新值 (newValue) 和旧值 (oldValue)。
  3. 模板绑定:在模板中使用 v-model 将输入框与 message 绑定,使得用户在输入框中的输入会实时更新 message 的值。
  4. 控制台输出:每当 message 的值发生变化时,回调函数会在控制台输出变化前后的值。

通过这种方式,你可以方便地监听和响应数据的变化。

上一篇:vue3 createvnode

下一篇:vue 修饰符

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站