vue2和vue3数组的响应式对比
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试数组响应式实例</title>
<!-- vue2 -->
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<!-- vue3 -->
<!-- <script src="https://unpkg.com/vue@next"></script> -->
</head>
<body>
<div id="app">
<h1>一维数组(length={{message.length}})</h1>
<p v-for="item in message">{{item}}</p>
<h1>JSON数组(length={{message1.length}})</h1>
<p v-for="item in message1">{{item.name}}</p>
</div>
<script>
console.log(typeof(Vue))
if(typeof(Vue) === 'function'){//vue2走这,可更换引入的js切换到vue3
new Vue({
el: '#app',
data() {
return {
message: [
1,
],
message1: [
{name:'name'},
],
}
},
mounted() {
setTimeout(()=>{
//操作一维数组, 一个个试,不要一次性打开多个
this.message[0] = 111 //不触发更新
// this.message.length = 99 //不触发更新
// this.message.push(222) //更新
// this.$set(this.message,2,333) //更新
//操作JSON数组
// this.message1[0] = {name:'name111'} //不触发更新
// this.message1.length = 99 //不触发更新
// this.message1.push({name:'name222'}) //更新
// this.$set(this.message1,2,{name:'name333'}) //更新
console.log('一维数组:',this.message)
console.log('JSON数组:',this.message1)
},2000)
},
})
}else if( typeof(Vue) ==='object'){ //vue3走这,可更换引入的js切换到vue2
const app = {
data() {
return {
message: [
1,
],
message1: [
{name:'name'},
],
}
},
mounted() {
setTimeout(()=>{
//操作一维数组, 一个个试,不要一次性打开多个
// this.message[0] = 111 //会更新
// this.message.length = 99 //会更新
// this.message.push(222) //会更新
// this.$set(this.message,2,333) //报错,vue3没有set方法
//操作JSON数组
// this.message1[0] = {name:'name111'} //会更新
// this.message1.length = 99 //会更新, 会报错可以先把<p v-for="item in message1">{{item.name}}</p>这块注释掉
// this.message1.push({name:'name222'}) //会更新
// this.$set(this.message1,2,{name:'name333'}) //报错,vue3没有set方法
console.log('一维数组:',this.message)
console.log('JSON数组:',this.message1)
},2000)
},
}
Vue.createApp(app).mount('#app')
}
</script>
</body>
</html>