14

一点 Vue.observable 想法

 4 years ago
source link: http://www.52cik.com/2020/02/29/vue-observable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue 2.6.0 新增了 Vue.observable api,但最近才去尝试使用它。

这东西说新也不新,因为他就是 vue 本身的功能,只是暴露出来,成为新 api 了。

在老版本中,直接用 new Vue({ data: {} }) 也一样。

API 本身

官方文档原文描述是: 让一个对象可响应。Vue 内部会用它来处理 data 函数返回的对象。

然后百度一下这个,几乎全是 使用Vue.observable()进行状态管理 这种文章。

谷歌一下也一样,然后你会发现,国内的文章都是翻译过来的。

所以我想试试能不能做点其他东西。

尝试

我创建了一个可响应对象, const state = Vue.observable({ count: 1 }); ,然后尝试挂载到 data 和 computed 下,发现都可以用,然后我在 state 上加了个方法。

const state = Vue.observable({ count: 1 });
state.add = () => state.count++;
const app = new Vue({
  data: {
    state,
  },
});

当挂载到 data 下,我发现 add 没被代理,所以推测 vue 直接挂载 Vue.observable 创建的对象。

尝试分页封装

我之前做分页,都需要 data 下挂个对象,然后需要计算属性计算当前显示列表。

现在我们可以尝试使用 Vue.observable 封装一个分页方法。

/**
 * 生成分页
 * @param {any[]} list 数据列表
 * @param {number} size 每页条数
 */
const pagination = (list, size = 10) => {
  const res = Vue.observable({
    /** 当前页码 */
    page: 1,
    /** 每页条数 */
    size,
    /** 总页数 */
    total: Math.ceil(list.length / size),
    /** 当前页显示数据 */
    list: [],
  });

  /** 原数组 */
  res.orgList = list;

  /** 分页方法 */
  res.setPage = (num) => {
    res.page += num
    const { page, size } = res;
    const pos = (page - 1) * size;
    res.list = res.orgList.slice(pos, pos + size);
  }

  // 初始化
  res.setPage(0);
  return res;
};

代码比较简化,没写 ajax 分页支持,就用最简单的例子来演示,以便于理解。

直接看下实例吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK