溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue組件如何修改根實(shí)例的數(shù)據(jù)

發(fā)布時(shí)間:2020-10-13 16:41:52 來(lái)源:億速云 閱讀:177 作者:小新 欄目:web開(kāi)發(fā)

這篇文章主要介紹Vue組件如何修改根實(shí)例的數(shù)據(jù),文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

思路:
1 在組件內(nèi)部監(jiān)聽(tīng)事件并把事件 emit
2 在組件上監(jiān)聽(tīng) emit 出來(lái)的事件
3 當(dāng)事件發(fā)生時(shí)執(zhí)行對(duì)應(yīng)的函數(shù)去修改根實(shí)例上的 data

實(shí)現(xiàn):
1 在組件內(nèi)部的 input框 中監(jiān)聽(tīng) input事件,并給 input事件 綁定    
 triggerInput函數(shù)
2 當(dāng)往 input框 中輸入內(nèi)容時(shí),觸發(fā) triggerInput 函數(shù)
 triggerInput函數(shù) 向外部 emit 一個(gè) edit事件 和 輸入框的值
3 在組件上監(jiān)聽(tīng)這個(gè) edit事件 并給 edit事件 綁定 triggerEdit函數(shù)
4 此時(shí)會(huì)觸發(fā) triggerEdit函數(shù),triggerEdit函數(shù) 就能去修改根實(shí)例上的 data

注意:
1 triggerEdit函數(shù) 的第一個(gè)參數(shù)為你想要修改的根實(shí)例 data 的 key
2 第二個(gè)參數(shù) $event 是套路,有這個(gè)參數(shù)才能在 triggerEdit函數(shù) 中獲取
 組件內(nèi)部 emit 出來(lái)的 input框的值
3 可以在 triggerEdit函數(shù)中 log 出組件內(nèi)部發(fā)生的 event

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      根實(shí)例的 data message:{{message}}
      <br>
      根實(shí)例的 data name:{{name}}
      <br>
      message:
      <component-demo1
        v-on:edit="triggerEdit('message', $event)"
      ></component-demo1>
      name:
      <component-demo1
        v-on:edit="triggerEdit('name', $event)"
      ></component-demo1>
    </div>
  </body>
  <script>
    Vue.component('component-demo1', {
      template: `
        <div>
          組件內(nèi)的 input:
          <input
            v-on:input='triggerInput'
          >
        </div>
      `,
      methods: {
        triggerInput: function (e) {
          this.$emit('edit', e.target.value)
        },
      },
    })
    var app = new Vue({
      el: '#app',
      data: {
        message: 'hello vue',
        name: 'gua',
      },
      methods: {
        triggerEdit: function (key, value) {
          this[key] = value
          console.log(event)
        }
      }
    })
  </script>
</html>

Vue組件如何修改根實(shí)例的數(shù)據(jù)

以上是Vue組件如何修改根實(shí)例的數(shù)據(jù)的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI