关于javascript:当v-model更改时更新值

Updating a value when v-model changes

我有一个文本输入,其中v-model将其值绑定到data。当此v-model值更改时,我还希望能够调用我的parse()函数,以更新也在data上的数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    <input
        id="user-input"
        type="text"
        v-model="userInput">

   <ul id="parsed-list">
      <li v-for="item in parsedInput">
          {{ item }}
     
</li>

   
</ul>



new Vue({
  el: '#app',
  data: {
    userInput: '',
    parsedInput: []
  }
})

let parse = input => {
    return input.split(',')
}

如何使用v-model更改使用parse()函数更新data.parsedInput? Vue这样做的正确方法是什么?


依赖于另一个属性的数据属性的正确Vue方式是带有计算属性,只要userInput发生更改,该方式parsedInput就会自动更新:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let parse = input => {
  return input.split(',')
}

new Vue({
  el: '#app',
  data: {
    userInput: '',
  },
  computed: {
    parsedInput() {
        return parse(this.userInput)
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js">
<body>
 
    <input id="user-input" type="text" v-model="userInput">

    <ul id="parsed-list">
      <li v-for="item in parsedInput">
        {{ item }}
     
</li>

   
</ul>

 
</body>

作为旁注:为了防止is not defined错误,请在使用parse函数之前对其进行声明。