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

在此之前我是这样写的:

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,
});

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

阅读 2.8k
1 个回答

你为啥不直接声明一个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)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题