专业的编程技术博客社区

网站首页 > 博客文章 正文

Vue3教程 3.响应式ref函数(vue实现响应式的原理)

baijin 2024-10-04 13:24:12 博客文章 6 ℃ 0 评论

我们使用Vue3的setup,触发数据改变,但是数据不会及时更新到页面上,代码如下:

  <h2>{{ title }}</h2>
  <h2>{{ num }}</h2>
  <ul>
    <li v-for="(category, index) in categorys" :key="index">
        {{ category }}
    </li>
  </ul>
  <button @click="hello">hello</button>
export default {
  name: 'App',
  setup(){
    let title = '商品分类';
    let num = 30;
    let categorys = ['女装', '男装', '家电'];
    return {
      title,
      num,
      categorys,
      hello () {
        num += 1;
        categorys.push('数码');
      }
    }
  }
}

在Vue2定义的数据默认响应式,更改过数据后页面自动更新。但在Vue3的setup做响应式需要额外用上ref,代码如下:

import {ref} from 'vue';

export default {
  name: 'App',
  setup(){
    let title = ref('商品分类');
    let num = ref(30);
    let categorys = ref(['女装', '男装', '家电']);
    return {
      title,
      num,
      categorys,
      hello () {
        num.value += 1;
        categorys.value.push('数码');
      }
    }
  }
}

被ref包裹之后会返回RefImpl对象,使用时必须用.value

// 复杂对象包裹
let prodcut = ref({
    title: '电视机',
    sku: [{
        count: 2,
        title: '红色'
    }]
});
// 修改数据
let hello = () => {
    prodcut.value.sku[0].title = '蓝色';
}

return {
    prodcut,
    hello
}



Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表