Basic usage of ref

basic use

The ref function can wrap simple data types into responsive data (complex types are also available). Note that when manipulating values ​​in JS, you need to add attributes, and you can use them normally in the .valuetemplate.

 

<template>
  <div class="container">
    <div>{
   
   { name }}</div>
    <button @click="updateName">修改数据</button>
  </div>
</template>
<script>
  import { ref } from 'vue'
  export default {
    name: 'App',
    setup() {
      const name = ref('ifer')
      const updateName = () => {
        name.value = 'xxx'
      }
      return { name, updateName }
    }
  }
</script>

wrapping complex data types

Note: ref can actually wrap complex data types as responsive data. Generally, it is recommended to use ref when the data type is not determined, such as the data returned by the backend.

 

<template>
  <div class="container">
    <div>{
   
   { data?.name }}</div>
    <button @click="updateName">修改数据</button>
  </div>
</template>
<script>
  import { ref } from 'vue'
  export default {
    name: 'App',
    setup() {
      // 初始值是 null
      const data = ref(null)
      setTimeout(() => {
        // 右边的对象可能是后端返回的
        data.value = {
          name: 'ifer'
        }
      }, 1000)
      const updateName = () => {
        data.value.name = 'xxx'
      }
      return { data, updateName }
    }
  }
</script>

Guess you like

Origin blog.csdn.net/css_javascrpit/article/details/123969186