vue3+ts 中如何在axios获取数据时对ref对象中的属性进行解构赋值?

作者站长头像
站长
· 阅读数 22

在此之前我是这样写的:

const createTime = ref("");
const articleUserId = ref(""); //创建商品的角色的id
const role = ref(""); //查看商品的用户角色
const tagname = ref("");
const url = ref("");
const examine = ref(); //是否通过审核?
const title = ref(""); //商品名称
const price = ref(); //商品价格
const prePrice = ref(); //商品优惠价格
const pic = ref(""); //商品封面

//这是axios中的语句
    pic.value = res.data.pic;
    title.value = res.data.title;
    price.value = res.data.price;
    prePrice.value = res.data.prePrice;
    examine.value = res.data.examine;
    url.value = res.data.url;
    articleUserId.value = res.data.user.id;

现在我想声明一个带类型的ref对象,然后使用解构赋值来简化一些代码。老实说我不知道对象的解构能否将值赋给已经声明的对象的属性。

现在我的ref属性和给ref的泛型传的类型是这样的:

type ArticleContent = Omit<
  Article,
  "id" | "updateTime" | "downVote" | "upVote"
>;
const articleContent = ref<ArticleContent>({
  createTime: "",
  examine: 0,
  pic: "",
  prePrice: 0,
  price: 0,
  tags: [] as Tag[],
  title: "",
  url: "",
  user: {} as User,
});

我的想法是减少一些看起来很烂的代码,如果我的思路是错误的,能否告诉我该如何优化呢?

回复
1个回答
avatar
test
2024-07-16

你为啥不直接声明一个reactive对象

const articleContent = reactive<ArticleContent>({
  createTime: "",
  examine: 0,
  pic: "",
  prePrice: 0,
  price: 0,
  tags: [] as Tag[],
  title: "",
  url: "",
  user: {} as User,
})

axios拿到数据之后

Object.assign(articleContent, res.data as ArticleContent)
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容