1.vue3.0 setup,reactive、onMounted等生命周期函数、computed计算属性、toRefs、toRef、父子组件调用等应用,如下demo(需要安装ts)!
父组件:
<template>
<div class="about">
<span>今天是星期 {{week}}</span><br />
<span>你今年多大了{{age}}</span>
<h1>This is an about page</h1>
<span>{{ myNumber }}<br />readersNumber值为:{{ readersNumber }}<br /></span
><br />
<button @click="changeMyName">myNumber</button>
<HelloWorld msg='虎力全开' year='2022' @clickIt="handClick"/>
</div>
</template>
<script lang='ts'>
// 父组件
import { defineComponent, reactive, ref, toRef, toRefs, onMounted } from "vue"
// import { toRef, toRefs } from "@vue/reactivity"
import HelloWorld from '@/components/HelloWorld.vue'
export default defineComponent({
name: "AboutView",
components: {
HelloWorld
},
props: {
title: String
},
setup (props) {
const data = reactive({
myNumber: 1,
week: "星期*",
age: 0
})
console.log('当前组件的props=', props)
const readersNumber = ref(0) // 解决-基本数据类型-数据响应式问题
console.log("readersNumber=", readersNumber.value)
onMounted(() => {
data.week = new Date().getDay().toString()
console.log('Component is mounted!')
})
const age = toRef(data, 'age') // toRef解决一开始未在data中定义的属性,使其依然具有响应式,如果不使用
// lang='ts',则const age = toRef(data, 'age')段代码不会抛错,使用后自然提示age未定义
const changeMyName = () => { // 定义方法
data.myNumber++
}
const handClick = () => {
console.log('子组件调用了父组件的方法!')
}
setTimeout(() => { data.age = 30; readersNumber.value = 100 }, 3000) // data.age 与 age.value区别
return {
...toRefs(data), // 解决-解构-赋值数据响应式问题
changeMyName,
handClick,
age,
readersNumber
}
}
})
</script>
子组件:
<template>
<div class="hello">
<h1 @click="postMessageToParent">{{myInfo}}:{{ msg }}</h1>
<span>{{num}}</span>
<button @click='changeNumber'>changeNumber</button>
</div>
</template>
<script lang="ts">
// 子组件
import { computed, defineComponent, onMounted, reactive, toRefs } from 'vue'
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String,
year: String
},
setup (props, context) {
const data = reactive({
myInfo: '',
num: 4
})
console.log(props)
const { attrs, emit } = context // context 上下文
console.log(attrs)
const postMessageToParent = () => {
emit('clickIt')
}
const changeNumber = () => {
data.num++
}
onMounted(() => {
console.log(data.myInfo)
data.myInfo = props.year as string // ts语法
})
const num = computed(() => {
return data.num + 8
})
return {
...toRefs(data),
num,
postMessageToParent,
changeNumber
}
}
})
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
2.响应原理:
Vue2:深入响应式原理 — Vue.js
把一个普通的JS对象传入Vue实例作为data选项,Vue将遍历此对象所有的property,并使用Object.defineProperty把这些property转化为getter和setter进而实现双向数据绑定
Vue3:深入响应性原理 | Vue.js
Vue 将传入对象包裹在一个带有 get
和 set
处理程序的Proxy中实现双向数据绑定
3.v-if与v-for优先级
Vue2版本,v-for优先级高于v-if优先级,但有报错提示,不影响运行
Vue3版本,同时使用程序抛错,不能运行。
4.v-bind 属性合并
对于唯一属性,比如id,会后者覆盖前者;class类名,合并共存不变
5.ref变化,Vue3.0则如1中demo ref的变化
Vue2中: