Array1和Array2都是通过v-model绑定到同一个数组变量上,为啥Array1更新的时候Array2不能同步更新?
运行效果:
可以看到Array1都已经emit了input,但是Array2的updated为啥没有被调到?
模版代码:
<script src="//unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div>
Array1: <array-input v-model="result" />
</div>
<div>
Array2: <array-input v-model="result" />
</div>
<div>
result: {{result}}
</div>
</div>
<h3>logs:</h3>
<ol id="logs"></ol>
script代码:
let ArrayInputId = 0;
const ArrayInput = {
props: {
value: {
type: Array,
default: () => [],
},
},
template: '<input type="text" @input="onInputText" placeholder="Enter comma separated array" />',
data(){
return {
id: ++ArrayInputId,
text: '',
}
},
methods: {
onInputText(e){
this.text = e.target.value
let newValue = this.text.split(',')
log(`ArrayInput#${this.id} emit input: ${JSON.stringify(newValue)}, text: ${this.text}`)
this.$emit('input', newValue)
}
},
updated(){
log(`ArrayInput#${this.id} updated. value: ${JSON.stringify(this.value)}, text: ${this.text}`)
if (this.text !== this.value.join(',')){
this.text = this.value.join(',')
// this.$forceUpdate() // $forceUpdate not help ...
}
}
}
new Vue({
components: {
'array-input': ArrayInput,
},
data(){
return {
result: [],
}
}
}).$mount('#app')
function log(msg){
console.log(msg)
let li = document.createElement('li')
li.innerText = msg
document.getElementById('logs').appendChild(li)
}