为什么 Javascript 看不到 VueJS 创建的新元素?



>javascript 在渲染列表时看不到 vuejs 添加的新元素。

我创建了一个简单的代码,单击列表项后,它会在控制台中打印其对象:

<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
li {
font-size: 35px;
cursor: pointer;
padding-bottom: 5px;
}
.red {
color: red;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li v-for="item in array">{{item}}</li>
</ul>
<button type="button" name="button" v-on:click="update">Update Array</button>
</div>
</body>
<!-- VueJS Script -->
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: function () {
return {
array: [1, 2, 3, 4]
};
},
methods: {
update: function () {
app.array = [1, 2, 3, 4, 5, 6, 7, 8];
}
}
})
</script>
<!-- JQuery Script -->
<script type="text/javascript">
$("li").click(function () {
console.log(this);
});
</script>
</html>

只有事先更新数组才能正常工作,当我向数组添加新元素时,JS无法处理新项目。为什么?

jQuery将其单击处理程序绑定到jQuery代码运行时存在的li元素。 当 Vue 稍后添加新的li元素时,它们没有附加该点击处理程序,因为 Vue 不知道您使用非 Vue 代码附加了它们。 (出于同样的原因,Vue 可能对 DOM 进行的其他需要重建列表的更新可能会破坏 jQuery 绑定,即使是最初拥有它们的元素。

你可以通过使用来自父元素的委托事件来解决这个问题,该事件在 jQuery 运行时存在,Vue 以后不会修改该事件:

$('#app').on("click", "li", function() {...})

。但更好的解决方案是首先避免尝试混合 jQuery 和 Vue 代码,这样您就不会遇到这些问题,因为它们争夺 DOM 的控制权。

将这些处理程序放在 Vue 中,框架将在需要更新 DOM 时包含它们:

var app = new Vue({
el: '#app',
data: function() {
return {
array: [1, 2, 3, 4]
};
},
methods: {
update() { // <-- changed to ES6 arrow function shorthand, to preserve `this`
this.array = [1, 2, 3, 4, 5, 6, 7, 8]; // `this` refers to the current component; you often won't have an external variable name like `app` to refer to here
},
handleClick(item) {
console.log(item) // You probably want the data, not the DOM element (but if necessary the element would be the `event.target`)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
<ul>
<li v-for="item in array" v-on:click="handleClick(item)">{{item}}</li>
</ul>
<button type="button" name="button" v-on:click="update">Update Array</button>
</div>

最新更新