computed
computed在vue中起到计算属性作用。
<p>firstName: <input type="text" v-model="firstName"></p><p>lastName: <input type="text" v-model="lastName"></p><p>name: {{name}}</p>data() {return {firstName: '',lastName: ''};},computed: {name: {set() {//set值触发},get() {return this.lastName + ' ' + this.firstName}}}// andcomputed: {name() {return this.lastName + ' ' + this.firstName}}
watched
watch在vue起到观察监听的作用
<template><div>//我们在getFullName方法中改变了name的值,触发watch打印'invoked watch'<p>firstName: <input type="text" v-model="firstName" @input="getFullName"></p><p>lastName: <input type="text" v-model="lastName" @input="getFullName"></p><p>name: {{name}}</p></div></template><script>export default {data() {return {firstName: '',lastName: '',name: ''};},watch: {name(newD, oldD) {//newD最新的值,oldD改变之前的值console.log('invoked watch');}},methods: {getFullName() {this.name = this.lastName + this.firstName}}};</script>
如果觉得《vue中computed和watched的区别》对你有帮助,请点赞、收藏,并留下你的观点哦!