ref对比reactive.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <!-- eslint-disable vue/multi-word-component-names -->
  2. <script lang="ts" setup name="TheWelcome">
  3. import { reactive, ref } from 'vue';
  4. // 使用`reactive`创建响应式对象
  5. const car = reactive({
  6. brand: "奔驰",
  7. price: 100
  8. });
  9. // 使用`ref`创建响应式数字
  10. const sum = ref(0);
  11. function changePrice() {
  12. car.price += 10;
  13. }
  14. function changeCar() {
  15. // 错误用法
  16. //Object.assign(car, {brand: "马萨拉蒂", price: 10});
  17. Object.assign(car,{brand: "马萨拉蒂", price: 10})
  18. }
  19. function changeBrand() {
  20. car.brand = '宝马';
  21. }
  22. function changeSum() {
  23. sum.value += 1;
  24. }
  25. </script>
  26. <template>
  27. <!-- 主要容器,应用了`.HelloWorld`类以应用样式 -->
  28. <div class="HelloWorld">
  29. <h2>汽车信息:一辆{{ car.brand }}车, 价值{{ car.price }}万</h2>
  30. <button @click="changePrice">增加价格</button>
  31. <button @click="changeBrand">修改车型</button>
  32. <button @click="changeCar">修改一辆车</button>
  33. <hr>
  34. <h2>当前求和:{{ sum }}</h2>
  35. <button @click="changeSum">点击加一</button>
  36. </div>
  37. </template>
  38. <style scoped>
  39. /*
  40. .HelloWorld 类选择器,仅应用于当前组件内部的元素,
  41. 因为使用了`scoped`属性,确保样式不会影响到其他组件
  42. */
  43. .HelloWorld {
  44. background-color: skyblue; /* 设置背景颜色 */
  45. box-shadow: 0 0 10px; /* 添加阴影效果 */
  46. border-radius: 10px; /* 设置圆角半径 */
  47. padding: 20px; /* 设置内边距 */
  48. }
  49. /* 设置按钮之间的间距 */
  50. button {
  51. margin: 0 5px;
  52. }
  53. li {
  54. font-size: 20px;
  55. }
  56. </style>