响应式原理
- vue2响应式原理采用 Object.defineProperties 监听对象的getter与setter
- Vue3 pxoy代理的方式监听对象
启动方式
- vue2
new Vue({
store,
router,
render:h=>h(App)
}).$mount(“#app”) - vue3
import {createApp} from ‘vue’
createApp(App).use(store).use(router).mount(‘#app’)
var app = createApp(App)
app.config.globalProperties.$http = axios
app.config.globalProperties.$say = function(msg="我爱我的祖国"){ alert(msg)}
app.use(store).use(router).mount('#app')
全局方法定义
- vue2
Vue.prototype.$http = axios - Vue3
var spp = cerateApp(App)
app.config.globalProperies.$http = axios
template根组件
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
<div>你好vue</div>
</template>
生命周期
- Vue2
创建前后 beforeCreate,created
挂载前后 beforeMount,mounted
更新前后 beforeUpdate,updated
销毁前后 beforeDestroy,destroyed - Vue3
创建前后 beforeCreate,created
挂载前后 beforeMount,mounted
更新前后 beforeUpdate,updated
卸载切换 beforeUnmount,unmounted
<template>
<div>
<button @click="num++">{{num}}</button>
<button @click="setNum()">改变为5</button>
<div v-for="item in list" :key="item">
{{item}}
<button @click="list.splice(index,1)">×</button>
</div>
<p>{{twiceNum}}</p>
<p ref="myp">我爱我的祖国</p>
</div>
</template>
<script>
import {ref,reactive,watch,watchEffect,computed,onMounted} from 'vue'
export default {
setup(){
const num = ref(5);
const list = reactive(["vue","react","angular"])
function setNum(){
num.value = 5
}
watch(num,function(nval,oval){
console.log("num由",oval,"变化为",nval)
})
watchEffect(()=>{
console.log(num.value,list[1],'变化了')
})
var twiceNum = computed(()=>num.value*2)
var myp = ref(null)
onMounted(()=>{
console.log("组件已经挂载完毕")
myp.value.addEventListener("click",()=>alert(myp.value.innerText))
})
return {num,list,setNum,twiceNum,myp}
}
}
</script>