菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP 如何 W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA 生成式 AI SCIPY AWS 网络安全 数据科学
     ❯   

Vue 教程

Vue 首页 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue 为什么、如何及设置 Vue 首个 SFC 页面 Vue 组件 Vue Props Vue v-for 组件 Vue $emit() Vue 穿透属性 Vue 局部作用域样式 Vue 局部组件 Vue 插槽 Vue v-slot Vue 局部作用域插槽 Vue 动态组件 Vue Teleport Vue HTTP 请求 Vue 模板引用 Vue 生命周期钩子 Vue Provide/Inject Vue 路由 Vue 表单输入 Vue 动画 Vue v-for 动画 Vue 构建 Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue $watch() 方法


示例

使用 $watch() 方法创建一个监听器,每当 'value' 数据属性改变时,它都会写入一条新消息。

mounted() {
  this.$watch('value', function() {
    this.results.push('$watch() method')
  })
}
运行示例 »

更多示例请参见下方。


定义和用法

$watch() 方法用于创建监听器。

$watch() 方法返回一个停止函数,我们可以用它来停止监听器。(参见示例 4

监听器用于监视值的变化(第一个参数),并在发生变化时执行操作(第二个参数)。也可以为监听器定义其他属性(第三个参数)。

参数 描述
监听源 必需。第一个参数是监听源。这可以是一个组件属性名称字符串(上面的示例),一个简单的点分隔路径字符串(示例 5),或一个函数(示例 6)。
回调函数 必需。第二个参数是一个回调函数,当监听源发生变化时运行。回调函数可以设置为接收监听源的新旧值作为参数(参见示例 1)。
选项对象 可选。在这里我们可以指定 deep、immediate、flush 和 onTrigger/onTrack 选项。

deep: 默认值为 'false'。如果监听器是深度监听的,它还会对监听器所设置的属性内部更深层次的更改做出反应。(参见示例 2

immediate: 默认值为 'false'。在创建后立即触发监听器。当 'immediate' 设置为 'true' 时,监听器首次触发时,旧值将为 'undefined'。(参见示例 3

flush: 默认值为 'pre'。指定回调函数相对于组件渲染何时运行。可能的值为 'pre'、'post' 和 'sync'。请谨慎使用此 flush 选项。

onTrigger/onTrack: 用于调试。仅在开发模式下有效。

注意: 监听器也可以使用 watch 选项创建。


更多示例

示例 1

使用 $watch() 方法,每当 'value' 数据属性改变时,都会写入一条包含新旧值的新消息。

<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to change the value so that the $watch() method is triggered. The callback function writes a message with the new and old values.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      results: []
    };
  },
  mounted() {
    this.$watch('value', function(newVal, oldVal) {
      this.results.push('Old value:'+oldVal+', new value: '+newVal)
    })
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

示例 2

使用 $watch() 方法并将 deep 监听选项设置为 'true'。现在,监听器可以检测到 'value' 对象内部更深层次的更改。

<template>
  <h2>Example $watch() Method</h2>
  <p>Register an extra hobby for Stuart. The hobbies are stored in an array inside the 'value' object. The $watch() method
    is triggered because the 'deep' option is set to 'true' so that the watcher also detects changes further inside the
    object.</p>
  <div>
    <p>Register an extra hobby for Stuart:</p>
    <p><input type="text" ref="inpText"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        hobbies: ['Bird watching', 'Trail running']
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.hobbies.push(this.$refs.inpText.value);
      this.$refs.inpText.value = null;
      this.$refs.inpText.focus();
    }
  },
  mounted() {
    this.$watch('value', function () {
      this.watchMessages.push('watcher triggered')
    }, {
      deep: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li {
  background-color: lightgreen;
}</style>
运行示例 »

示例 3

使用 $watch() 方法并将 immediate 监听选项设置为 'true'。现在,监听器在创建后也会立即触发。

<template>
  <h2>Example $watch() Method</h2>
  <p>With the 'immediate' option set to 'true' the watcher is also triggered right after it is created.</p>
  <div>
    <input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}
    <p>Messages from the watcher:</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch('value', (newVal, oldVal) => {
      this.watchMessages.push('Old value: '+oldVal+' New value: '+newVal)
    }, {
      immediate: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li:first-child {
  background-color: lightgreen;
}</style>
运行示例 »

示例 4

使用 $watch() 方法返回的停止函数来停止监听器。

<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to see the watcher work, click the stop button, and drag the slider again to confirm that the watcher has now stopped.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <button v-on:click="stopFunc">Stop Watcher</button>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      results: [],
      stopFunc: null
    };
  },
  mounted() {
    this.stopFunc = this.$watch('value', function() {
      this.results.push('$watch() method')
    })
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

示例 5

使用点分隔路径字符串,以便 $watch() 方法可以监听 'value' 对象中的 'country' 属性。

<template>
  <h2>Example $watch() Method</h2>
  <p>The watcher is set up to watch 'value.country' and will therefore detect when the country is changed inside the 'value' object.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p><input type="text" v-model="inpVal"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      inpVal: null,
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        country: 'Mexico'
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.country = this.inpVal;
      this.inpVal = null;
    }
  },
  mounted() {
    this.$watch('value.country', function () {
      this.watchMessages.push('watcher triggered')
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

示例 6

$watch() 方法中使用函数来监听多个值的变化。

<template>
  <h2>Example $watch() Method</h2>
  <p>Using a function as the first argument in the watcher to watch for changes in the sum of value A and value B.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p>Value A: <input type="range" min="-10" max="20" v-model="inpValA"> {{ inpValA }}</p>
    <p>Value B: <input type="range" min="-10" max="20" v-model="inpValB"> {{ inpValB }}</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inpValA: 2,
      inpValB: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch( 
      ()=> Number(this.inpValA) + Number(this.inpValB), 
      function (newVal,oldVal) {
        this.watchMessages.push('watcher triggered. A + B = ' + newVal)
      }
    );
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
li {
  background-color: lightgreen;
}
</style>
运行示例 »

相关页面

Vue 教程:Vue 监听器

Vue 教程: Vue 方法

Vue 教程: Vue v-on 指令

Vue 教程:Vue Template Refs

Vue 参考:Vue $refs 对象

JavaScript 教程:JS 箭头函数


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持