zoukankan      html  css  js  c++  java
  • Vue3 更改setup中定义的值不渲染到视图上【Vue2.x向Vue3.x的迁移(踩坑)日记】

    最近用vue3 重构vue2.x的项目,真是一坑未平,一波又起,话不多说 上代码

      <template>
        <div>{{ loadingStatus }}</div>
      </template>
      ...
      setup(props, context) {
        // @ts-ignore
        const { proxy } = getCurrentInstance();
        const typeClassName = computed(() => {
          return "xb-" + props.type;
        });
    
        let loadingStatus = ref(false);
        const handleClick = () => {
          if (props.autoLoading) {
            loadingStatus= true;
          }
          context.emit("click", () => {
            loadingStatus= false;
          });
        };
        return {
          loadingStatus,
          handleClick
        };
      }

    乍一看是不是没什么问题,但是视图上loadingStatus依然是false,为什么呢,setup内部打印出为true,于是我看文档突然。。。
    因为我们在使用Vue3的时候,通常使用ref来监听一些简单数据类型如数字、字符串、布尔等。你可能注意到一种现象,是更改ref的值的时候,需要使用ref.value的形式,(在template中使用ref时,Vue自动帮我们添加.value了,所以不需要我们手动添加),看起来很神奇,为什么会有一个.value呢?是因为ref本质上是一个包装过后的reactive。在你去定义ref的时候,Vue会内部帮我们包装一下。

    对于ref而言,因为ref是包装过的reactive,所以使用reactive就可以定义ref:

    let age = ref(18)
    // 等价于
    let age = reactive({value: 18})
    function ref(val) {
      return reactive({value: val})
    }

    所以最终代码:

      <template>
        <div>{{ loadingStatus }}</div>
      </template>
      ...
      setup(props, context) {
        // @ts-ignore
        const { proxy } = getCurrentInstance();
        const typeClassName = computed(() => {
          return "xb-" + props.type;
        });
    
        let loadingStatus = ref(false);
        const handleClick = () => {
          if (props.autoLoading) {
            loadingStatus.value= true;
          }
          context.emit("click", () => {
            loadingStatus.value= false;
          });
        };
        return {
          loadingStatus,
          handleClick
        };
      }

    一句话:修改ref需要.value 而 reactive 则不用

  • 相关阅读:
    Qt中的角度转弧度
    Qt5鼠标事件及实例
    POJ 2239 Selecting Courses【最大匹配】
    POJ 1325 Machine Schedule【最小点覆盖】
    POJ 1469 COURSES【二分图最大匹配】
    POJ 1274 The Perfect Stall【二分图最大匹配】
    poj2226Muddy Fields【最小点覆盖(建图的思路比较好)】
    hdu4160Dolls【最小路径覆盖】
    hdu2444The Accomodation of Students【判断二分图+最大匹配】
    HLG1407Leyni的游戏【最小点权覆盖集】
  • 原文地址:https://www.cnblogs.com/mica/p/14755741.html
Copyright © 2011-2022 走看看