怎样使用 Vue 的监听属性 watch ?

需求: 我需要在某个数据变化时能够执行特定的动作, 比如我在输入框中输入数字 88, 系统检测到以后就会弹窗 拜拜 , 而输入其他字符则不会触发, 这种需求简直多入牛毛, 实际上这就是 自定义事件 , 和 点击 / 按下 / 滚动 这种事件是一样的, 都是符合条件以后就执行特定代码. 在 vue 里面, 这个功能需要使用 watch.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
  <title>Vue Test</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model:value="inputValue" />
    </div>
    <script>
        var vApp = new Vue({
            el: "#app",
            data: {
                inputValue: ''
            }
        })
        // $watch 需要在 new Vue({}) 之外声明.
        vApp.$watch("inputValue", function(newValue, oldValue){
            console.log(newValue);
            if (newValue === "88") { alert("拜拜"); }
        })
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/aisowe/p/11431002.html