深層次下v-model與函數的自動調用


0. 緣起

之前做項目的時候遇到一個很陰間的問題,如果多層級了,el-input就無法根據綁定的v-model更新值,這個問題倒好解決,給他的輸入方法加個強制更新。

this.$forceUpdate();

<el-input
	v-else
    @input="onInput()"
    v-model="form[`${item.code}TemplateAlias`][index]"
    placeholder="請輸入內容"
></el-input>
    
    // methods
    onInput() {
      this.$forceUpdate();
    },

恩,輸入現在可以同步了,但!我發現這個輸入框綁定的v-model並沒有同步,或者說它值變化了,但依據該值的v-if/v-for沒有變化。搜索一番,說也可以用強制更新來解決。我試了並不行。

1. 原因

這玩意是用v-for做的,層層嵌套,太多層級了,導致模板渲染不過來。

          <div
            class="nameBox"
            v-for="(temp, index) in form[`${item.code}TemplateIds`]"
            :key="index"
          >
            <span>
              <!-- 公式Id:{{ temp }} -->
              <span class="exName">公式名稱:</span
              >{{ EXNameList[`${item.code}NameList`][index] }}</span
            >
            <div class="aliasBox">
              <span class="alias exName">公式別名:</span>

              <div class="editBox">
                <span v-if="getValue(item, index)">{{
                  form[`${item.code}TemplateAlias`][index]
                }}</span>
                <el-input
                  v-else
                  @input="onInput()"
                  v-model="form[`${item.code}TemplateAlias`][index]"
                  placeholder="請輸入內容"
                ></el-input>
                <el-button @click="showAlias(`${item.code}`, index)"
                  ><span v-if="getValue(item, index)">修改</span>
                  <span v-else>保存</span></el-button
                >
              </div>
            </div>
          </div>

2. 解決方法

實際上就在v-if/v-else的判斷條件中,用的是方法!

  methods: {
    getValue(item, index) {
      return this[`${item.code}ShowAlias`][index];
    }
  }

3. 相關內容

如果用函數就可以在每次實例化的時候都通過運行函數返回一個全新的 data,這樣我們就不會造成 data 之間的共享和混淆了。這樣在深層次情況下,也可以及時更新模板內容。

Vue 組件 data 為什么必須是個函數,而 Vue 的根實例卻沒有此限制? - 陳好人的回答 - 知乎 https://www.zhihu.com/question/384454093/answer/1122159865

——————下方為引用內容

當組件被創建后,會拿到data參數 。在源碼中 vue會判斷傳入的data是否是一個函數,如果是一個函數就會執行這個函數,此時會返回一個對象,然后賦值給data。

那我們都知道,對象存儲在棧中的是引用地址。假如說你直接向組件中傳入一個對象,當我們進行數據修改的時候,就會修改存放在地址(指針)上的值,也就導致了所有組件都發生了改變。

而如果data是一個函數,在傳入組件實例之后會執行此函數,並返回一個新的對象。也就相當於在棧中重新分配了引用地址。組件之間就不會共享data了。

[ data 為什么必須是個函數,而 Vue 的根實例卻沒有此限制?](Vue 組件 data 為什么必須是個函數,而 Vue 的根實例卻沒有此限制? - 自由的囚徒的回答 - 知乎 https://www.zhihu.com/question/384454093/answer/1510208514)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM