Vue3.0 - watch函数

前言

watch函数监听当某个值的改变,可以就此做一些事情(钩子函数)


监听ref对象

<body>
    <div id="app">
		<input v-model="firstName"/>
		<input v-model="lastName"/>
		<div>{{fullName}}</div>
	</div>
</body>
<script>

const {createApp, ref,  watch} = Vue;
const firstName = ref(‘‘);
const lastName = ref(‘‘);
let fullName = ref(‘‘);

const app = {
   // 入口函数
    setup() {
        // 监听ref对象
        watch(firstName, (newVal, oldVal) => {
            fullName.value = firstName.value + lastName.value;
        })
        // 监听ref对象
        watch(lastName, (newVal, oldVal) => {
            fullName.value = firstName.value + lastName.value;
        })
        return {
            firstName,
            lastName,
            fullName
        }
    }
}

// 挂载(建立vue与dom的联系)
createApp(app).mount(‘#app‘)
</script>

监听reactive对象

<body>
    <div id="app">
	<input v-model="name.firstName"/>
        <input v-model="name.lastName"/>
        <div>{{fullName}}</div>
	</div>
</body>
<script>

const {createApp, ref, reactive, watch} = Vue;
const name = reactive({
    firstName: ‘‘,
    lastName: ‘‘
})
let fullName = ref(‘‘);

const app = {
   // 入口函数
    setup() {
        // 监听reactive对象
        watch(name, (newVal, oldVal) => {
            fullName.value = name.firstName + name.lastName;
        })
        return {
            fullName,
            name
        }
    }
}

// 挂载(建立vue与dom的联系)
createApp(app).mount(‘#app‘)
</script>

监听reactive对象下的单个属性

<body>
    <div id="app">
	<input v-model="name.firstName"/>
        <input v-model="name.lastName"/>
        <div>{{fullName}}</div>
	</div>
</body>
<script>

const {createApp, ref, reactive, watch} = Vue;
const name = reactive({
    firstName: ‘‘,
    lastName: ‘‘
})
let fullName = ref(‘‘);

const app = {
   // 入口函数
    setup() {
        // 监听reactive对象下的单个属性
        watch(()=>name.firstName, (newVal, oldVal) => {
            fullName.value = name.firstName + name.lastName;
        })
        return {
            fullName,
            name
        }
    }
}

// 挂载(建立vue与dom的联系)
createApp(app).mount(‘#app‘)
</script>

- End -
梦想是咸鱼
关注一下吧
Vue3.0 - watch函数

Vue3.0 - watch函数

上一篇:Mybatis学习总结(二)—使用接口实现数据的增删改查


下一篇:在 Windows 上安装Rabbit MQ 指南