事例

検索フォームの値が変わったタイミングで自動的にAjaxを行なって結果を一覧表示

<div id="app">
    <p>{{ message }}</p>
    <p>
        <input type="text" v-model="message">
    </p>
</div>
const app = Vue.createApp({
    data: () => ({
        message: 'Hello VueJs'
    }),
    watch: {
        message: function (newValue, oldValue) {
            console.log('new: %s, old:%s', newValue, oldValue)
        }
    }
	  🔼messageを監視して、データに変更があれば関数が実行される
})
app.mount('#app')

算出プロパティ or 監視プロパティ

<div id="app">
    <p><input type="text" v-model="firstName">firstname</p>
    <p><input type="text" v-model="lastName">lastname</p>
    <p>fullName: {{ fullName }}</p>
</div>
🔽監視プロパティで記述
const app = Vue.createApp({
    data: () => ({
        firstName: '',
        lastName: '',
        fullName: ''
    }),
    watch: {
        firstName: function (value) {
            this.fullName = value + ' ' + this.lastName
        },
        lastName: function (value) {
            this.fullName = this.firstName + ' ' + value
        }
    }
})

🔽算出プロパティで記述
const app = Vue.createApp({
    data: () => ({
        firstName: '',
        lastName: '',
    }),
    computed: {
        fullName: function (value) {
            return this.firstName + ' ' + this.lastName
        },
    }
})
app.mount('#app')

🔼比較すると、算出プロパティの方がすっきりかけている

deepオプション

const app = Vue.createApp({
    data: () => ({
        colors: [
            { name: 'Red'},
            { name: 'Green'},
            { name: 'Blue'}
        ]
    }),
    watch: {
        colors: {
            handler: function (newValue, oldValue) {
                console.log('updated')
            },
        }
    },
		🔼下記のmethodsでデータが変更されても、変更されるデータが深いため、上記のwatchで検出ができない
    methods: {
        onClick: function () {
            this.colors[1].name = 'White'

        }
    }
})
app.mount('#app')