search
HomeWeb Front-endVue.jsHow to use computed properties and listeners in Vue3

Computed properties

We know that some data in data can be displayed directly through interpolation syntax in the template, but in some cases, we may need to perform some transformations on the data before displaying it, or we need to Combining multiple data for display

Using expressions in templates can be very convenient, but they are originally designed for simple operations. Putting too much logic in the template will make the template It is too heavy and difficult to maintain, and if it is used in multiple places, there will be a lot of duplicate code

So we hope to separate the business logic and UI interface. One way is to extract the logic into a method, but this approach has the following disadvantages

  • All the data usage process will become a method call

  • Multiple acquisitions Data needs to call the method multiple times to execute the corresponding logic without caching

In fact, For any complex logic that contains responsive data, you should use calculated properties

<div id="app">
  <!-- 计算属性的使用和普通状态的使用方式是一致的 -->
  <h3 id="nbsp-fullname-nbsp">{{ fullname }}</h3>
</div>

<script>
  Vue.createApp({
    data() {
      return {
        firstname: &#39;Klaus&#39;,
        lastname: &#39;Wang&#39;
      }
    },
    computed: {
      fullname() {
        return this.firstname + &#39; &#39; + this.lastname
      }
    }
  }).mount(&#39;#app&#39;)

Cache

Computed properties will be cached based on their dependencies. When the data does not change, calculated properties do not need to be recalculated

But if When the dependent data changes, the calculated properties will still be recalculated when used

And the interface will be re-rendered using the latest calculated property values

getters and setters

Computed properties In most cases, only one getter method is needed, so we will write the calculated properties directly as a function

<div id="app">
  <!-- 计算属性的使用和普通状态的使用方式是一致的 -->
  <h3 id="nbsp-fullname-nbsp">{{ fullname }}</h3>
  <button @click="change">change</button>
</div>
<script>
  Vue.createApp({
    data() {
      return {
        firstname: &#39;Klaus&#39;,
        lastname: &#39;Wang&#39;
      }
    },
    methods: {
      change() {
        this.fullname = &#39;Alex Li&#39;
      }
    },
    computed: {
      // 计算属性的完整写法
      fullname: {
        get() {
          return this.firstname + &#39; &#39; + this.lastname
        },
        set(v) {
          this.firstname = v.split(&#39; &#39;)[0]
          this.lastname = v.split(&#39; &#39;)[1]
        }
      }
    }
  }).mount(&#39;#app&#39;)
</script>

Listener

is defined in the object returned by data The data is bound to the template through interpolation syntax, etc. When the data changes, the template will automatically update to display the latest data

But in some cases, we hope that in the code logic To monitor changes in certain data, you need to use the listener watch at this time

Vue.createApp({
  data() {
    return {
      info: {
        name: &#39;Klaus&#39;
      }
    }
  },
  watch: {
    // 可以使用watch监听响应式数据的改变
    // 对应有两个参数
    // 参数一 --- 新值
    // 参数二 --- 旧值
    info(newV, oldV) {
      // 如果监听的值是对象,获取到的新值和旧值是对应对象的代理对象
      console.log(newV, oldV)

      // 代理对象 转 原生对象
      // 1. 使用浅拷贝获取一个新的对象,获取的新的对象为原生对象
      console.log({...newV})

      // 2. 使用Vue.toRaw方法获取原生对象
      console.log(Vue.toRaw(newV))
    }
  },
  methods: {
    change() {
      this.info = {
        name: &#39;Steven&#39;
      }
    }
  }
}).mount(&#39;#app&#39;)

Configuration options

Properties Description
deep Whether to turn on deep monitoring
The value is boolean
When it is not turned on, if the object is monitored, only the reference of the object occurs The watch callback will only be triggered when it changes
After starting, if the object is monitored, then as long as any attribute in the object changes, the watch callback will be triggered
immediate Whether to start monitoring immediately
By default, the watch monitoring will not be triggered for the first rendering. Only when the value changes, the watch monitoring will be triggered.
After setting immediate to true, the watch monitoring will be triggered for the first time. Rendering will also trigger watch monitoring. At this time, the value of oldValue is undefined
Vue.createApp({
  data() {
    return {
      info: {
        name: &#39;Klaus&#39;
      }
    }
  },
  watch: {
    info: {
      // 开启了深度监听后,当info的属性发生改变的时候,就会触发对应的watch回调
      // 注意: 和直接修改info引用不同的是,如果直接修改的是对象的属性
      // 那么此时newV和oldV是同一个对象的引用, 此时也就获取不到对应的旧值
      handler(newV, oldV) {
        console.log(newV, oldV)
        console.log(newV === oldV)  // => true
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    change() {
      this.info.name = &#39;Steven&#39;
    }
  }
}).mount(&#39;#app&#39;)

Other writing methods

Directly monitor the object properties

watch: {
  &#39;info.name&#39;(newV, oldV){
    console.log(newV, oldV)
  }
}

String writing method

Vue.createApp({
  data() {
    return {
      info: {
        name: &#39;Klaus&#39;
      }
    }
  },
  watch: {
    // watch的值如果是一个字符串的时候
    // 会自动以该字符串作为函数名去methods中查找对应的方法
    &#39;info.name&#39;: &#39;watchHandler&#39;
  },
  methods: {
    change() {
      this.info.name = &#39;Steven&#39;
    },
    watchHandler(newV, oldV){
      console.log(newV, oldV)
    }
  }
}).mount(&#39;#app&#39;)

Array writing method

Vue.createApp({
  data() {
    return {
      info: {
        name: &#39;Klaus&#39;
      }
    }
  },
  watch: {
    &#39;info.name&#39;: [
      &#39;watchHandler&#39;,

      function handle() {
        console.log(&#39;handler2&#39;)
      },

      {
        handler() {
          console.log(&#39;handler3&#39;)
        }
      }
    ]
  },
  methods: {
    change() {
      this.info.name = &#39;Steven&#39;
    },
    watchHandler(){
      console.log(&#39;handler1&#39;)
    }
  }
}).mount(&#39;#app&#39;)

$watch

Vue.createApp({
  data() {
    return {
      info: {
        name: &#39;Klaus&#39;
      }
    }
  },
  created() {
    /*
          $watch 参数列表
            参数一 --- 侦听源
            参数二 --- 侦听回调
            参数三 --- 配置对象
        */
    this.$watch(&#39;info.name&#39;, (newV, oldV) => console.log(newV, oldV), {
      immediate: true
    })
  },
  methods: {
    change() {
      this.info.name = &#39;Steven&#39;
    }
  }
}).mount(&#39;#app&#39;)

The above is the detailed content of How to use computed properties and listeners in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.